athrunwang

          紀元
          數(shù)據(jù)加載中……

          用org.apache.tools.zip壓縮/解壓縮zip文件

          寫了一個用org.apache.tools.zip壓縮/解壓縮zip文件的例子,用來解決中文亂碼問題。代碼如下:
          Java代碼  收藏代碼
          1. package org.coolyongzi;  
          2.   
          3. import java.io.File;  
          4. import java.io.FileInputStream;  
          5. import java.io.FileOutputStream;  
          6. import java.io.InputStream;  
          7. import org.apache.tools.zip.ZipEntry;  
          8. import org.apache.tools.zip.ZipFile;  
          9. import org.apache.tools.zip.ZipOutputStream;  
          10. import java.io.IOException;  
          11. import java.util.Enumeration;  
          12. import org.apache.log4j.LogManager;  
          13. import org.apache.log4j.Logger;  
          14.   
          15.   
          16. public class ZipTools {  
          17.     public static final Logger logger = LogManager.getLogger(FileTools.class);  
          18.     public ZipTools()  
          19.     {  
          20.           
          21.     }  
          22.     /* 
          23.      * @description:Compressed files or folders 
          24.      * @param compressedFilePath String,zipFileRootPath String,zipFileName String 
          25.      * @return boolean 
          26.      */  
          27.     public static boolean compressFloderChangeToZip(String compressedFilePath,String zipFileRootPath,String zipFileName)   
          28.     throws IOException  
          29.     {  
          30.         File compressedFile = new File(compressedFilePath);  
          31.         if("".equalsIgnoreCase(zipFileName))  
          32.         {  
          33.             zipFileName = StringTools.getShortFileNameFromFilePath(compressedFilePath);  
          34.         }  
          35.         if(!StringTools.conversionSpecialCharacters(zipFileRootPath).endsWith(File.separator))  
          36.         {  
          37.             zipFileRootPath = zipFileRootPath + File.separator;  
          38.         }  
          39.         ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream(zipFileRootPath + zipFileName));  
          40.         String base ="";  
          41.         logger.debug("compress [" + compressedFilePath + "] start!");  
          42.         boolean result = ZipTools.compressFloderChangeToZip(compressedFile,zipOutputStream,base);  
          43.         logger.debug("compress [" + compressedFilePath + "] end!");  
          44.         zipOutputStream.close();  
          45.         return result;  
          46.           
          47.     }  
          48.       
          49.     private static  boolean compressFloderChangeToZip(File compressedFile,ZipOutputStream zipOutputStream,String base)   
          50.     throws IOException  
          51.     {  
          52.         FileInputStream fileInputStream = null;  
          53.           
          54.         try{  
          55.             if(compressedFile.isDirectory())  
          56.             {  
          57.                 File[] childrenCompressedFileList = compressedFile.listFiles();  
          58.                 base = base.length() == 0 ? "" : base + File.separator;  
          59.                 for (int i = 0; i < childrenCompressedFileList.length; i++) {  
          60.                     ZipTools.compressFloderChangeToZip(childrenCompressedFileList[i],  
          61.                     zipOutputStream,base+childrenCompressedFileList[i].getName());  
          62.                 }  
          63.             }  
          64.             else  
          65.             {  
          66.                 if("".equalsIgnoreCase(base))  
          67.                 {  
          68.                     base = compressedFile.getName();  
          69.                 }  
          70.                 zipOutputStream.putNextEntry(new ZipEntry(base));  
          71.                 fileInputStream = new FileInputStream(compressedFile);  
          72.                 int b;  
          73.                 while((b=fileInputStream.read())!=-1)  
          74.                 {  
          75.                     zipOutputStream.write(b);  
          76.                 }  
          77.                 fileInputStream.close();  
          78.             }  
          79.             return true;  
          80.         }catch(Exception e)  
          81.         {  
          82.             e.getStackTrace();  
          83.             logger.error(e.getMessage());  
          84.             return false;  
          85.         }  
          86.     }  
          87.     /* 
          88.      * @param:zipFilePath String,releasePath String 
          89.      * @return void 
          90.      * @description:Decompress A File 
          91.      */  
          92.     @SuppressWarnings("unchecked")  
          93.     public static void decompressFile(String zipFilePath,String releasePath) throws IOException  
          94.     {  
          95.         ZipFile zipFile = new ZipFile(zipFilePath);  
          96.         Enumeration<ZipEntry> enumeration = zipFile.getEntries();  
          97.         InputStream inputStream = null;  
          98.         FileOutputStream fileOutputStream = null;  
          99.         ZipEntry zipEntry = null;  
          100.         String zipEntryNameStr ="";  
          101.         String[] zipEntryNameArray = null;  
          102.         while (enumeration.hasMoreElements()) {  
          103.             zipEntry = enumeration.nextElement();  
          104.             zipEntryNameStr = zipEntry.getName();  
          105.             zipEntryNameArray = zipEntryNameStr.split("/");  
          106.             String path = releasePath;  
          107.             File root = new File(releasePath);  
          108.             if(!root.exists())  
          109.             {  
          110.                 root.mkdir();  
          111.             }  
          112.             for (int i = 0; i < zipEntryNameArray.length; i++) {  
          113.                 if(i<zipEntryNameArray.length-1)  
          114.                 {  
          115.                     path = path + File.separator+zipEntryNameArray[i];        
          116.                     new File(StringTools.conversionSpecialCharacters(path)).mkdir();  
          117.                 }                 
          118.                 else  
          119.                 {  
          120.                     if(StringTools.conversionSpecialCharacters(zipEntryNameStr).endsWith(File.separator))  
          121.                     {  
          122.                         new File(releasePath + zipEntryNameStr).mkdir();  
          123.                     }  
          124.                     else  
          125.                     {  
          126.                         inputStream = zipFile.getInputStream(zipEntry);  
          127.                         fileOutputStream = new FileOutputStream(new File(  
          128.                                 StringTools.conversionSpecialCharacters(releasePath + zipEntryNameStr)));     
          129.                         byte[] buf = new byte[1024];  
          130.                         int len;  
          131.                         while ((len = inputStream.read(buf)) > 0)  
          132.                         {  
          133.                             fileOutputStream.write(buf, 0, len);  
          134.                         }  
          135.                         inputStream.close();  
          136.                         fileOutputStream.close();  
          137.                     }  
          138.                 }  
          139.             }  
          140.         }  
          141.         zipFile.close();  
          142.     }  
          143. }  

          junit測試類
          Java代碼  收藏代碼
          1. package org.coolyongzi.testcase;  
          2.   
          3. import java.io.IOException;  
          4.   
          5. import org.coolyongzi.ZipTools;  
          6.   
          7. import junit.framework.TestCase;  
          8.   
          9. public class ZipToolsTest extends TestCase {  
          10.   
          11.     protected void setUp() throws Exception {  
          12.         super.setUp();  
          13.     }  
          14.   
          15.     protected void tearDown() throws Exception {  
          16.         super.tearDown();  
          17.     }  
          18.   
          19.     public void testCompressFloderChangeToZip(){  
          20.         try {  
          21.             ZipTools.compressFloderChangeToZip("f:/iDocumentBanner2.gif", "f:", "test.zip");  
          22.         } catch (IOException e) {  
          23.             // TODO Auto-generated catch block  
          24.             e.printStackTrace();  
          25.         }  
          26.     }  
          27.       
          28.     public void testDecompressFile(){  
          29.         try {  
          30.             ZipTools.decompressFile("f:/java對解壓Zip格式的文件.zip","f:/test/");  
          31.         } catch (IOException e) {  
          32.             // TODO Auto-generated catch block  
          33.             e.printStackTrace();  
          34.             System.out.println(e.getMessage());  
          35.         }  
          36.     }  
          37. }

          posted @ 2012-01-03 17:32 AthrunWang 閱讀(5272) | 評論 (0)編輯 收藏
          使用org.apache.tools.zip實現(xiàn)zip壓縮和解壓

          原創(chuàng)作品,允許轉(zhuǎn)載,轉(zhuǎn)載時請務(wù)必以超鏈接形式標明文章 原始出處 、作者信息和本聲明。否則將追究法律責任。http://wintys.blog.51cto.com/425414/90878
          import java.io.*;
          import org.apache.tools.zip.*;
          import java.util.Enumeration;
          /**
          *功能:zip壓縮、解壓(支持中文文件名)
          *說明:本程序通過使用Apache Ant里提供的zip工具org.apache.tools.zip實現(xiàn)了zip壓縮和解壓功能.
          *   解決了由于java.util.zip包不支持漢字的問題。
          *   使用java.util.zip包時,當zip文件中有名字為中文的文件時,
          *   就會出現(xiàn)異常:"Exception  in thread "main " java.lang.IllegalArgumentException  
          *               at   java.util.zip.ZipInputStream.getUTF8String(ZipInputStream.java:285)
          *注意:
          *   1、使用時把ant.jar放到classpath中,程序中使用import org.apache.tools.zip.*;
          *   2、Apache Ant 下載地址:[url]http://ant.apache.org/[/url]
          *   3、Ant ZIP API:[url]http://www.jajakarta.org/ant/ant-1.6.1/docs/mix/manual/api/org/apache/tools/zip/[/url]
          *   4、本程序使用Ant 1.7.1 中的ant.jar
          *
          *僅供編程學習參考.
          *
          *@author Winty
          *@date   2008-8-3
          *@Usage:
          *   壓縮:java AntZip -zip "directoryName"
          *   解壓:java AntZip -unzip "fileName.zip"
          */

          public class AntZip{
              private ZipFile         zipFile;
              private ZipOutputStream zipOut;     //壓縮Zip
              private ZipEntry        zipEntry;
              private static int      bufSize;    //size of bytes
              private byte[]          buf;
              private int             readedBytes;
              
              public AntZip(){
                  this(512);
              }

              public AntZip(int bufSize){
                  this.bufSize = bufSize;
                  this.buf = new byte[this.bufSize];
              }
              
              //壓縮文件夾內(nèi)的文件
              public void doZip(String zipDirectory){//zipDirectoryPath:需要壓縮的文件夾名
                  File file;
                  File zipDir;

                  zipDir = new File(zipDirectory);
                  String zipFileName = zipDir.getName() + ".zip";//壓縮后生成的zip文件名

                  try{
                      this.zipOut = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zipFileName)));
                      handleDir(zipDir , this.zipOut);
                      this.zipOut.close();
                  }catch(IOException ioe){
                      ioe.printStackTrace();
                  }
              }

              //由doZip調(diào)用,遞歸完成目錄文件讀取
              private void handleDir(File dir , ZipOutputStream zipOut)throws IOException{
                  FileInputStream fileIn;
                  File[] files;

                  files = dir.listFiles();
              
                  if(files.length == 0){//如果目錄為空,則單獨創(chuàng)建之.
                      //ZipEntry的isDirectory()方法中,目錄以"/"結(jié)尾.
                      this.zipOut.putNextEntry(new ZipEntry(dir.toString() + "/"));
                      this.zipOut.closeEntry();
                  }
                  else{//如果目錄不為空,則分別處理目錄和文件.
                      for(File fileName : files){
                          //System.out.println(fileName);

                          if(fileName.isDirectory()){
                              handleDir(fileName , this.zipOut);
                          }
                          else{
                              fileIn = new FileInputStream(fileName);
                              this.zipOut.putNextEntry(new ZipEntry(fileName.toString()));

                              while((this.readedBytes = fileIn.read(this.buf))>0){
                                  this.zipOut.write(this.buf , 0 , this.readedBytes);
                              }

                              this.zipOut.closeEntry();
                          }
                      }
                  }
              }

              //解壓指定zip文件
              public void unZip(String unZipfileName){//unZipfileName需要解壓的zip文件名
                  FileOutputStream fileOut;
                  File file;
                  InputStream inputStream;

                  try{
                      this.zipFile = new ZipFile(unZipfileName);

                      for(Enumeration entries = this.zipFile.getEntries(); entries.hasMoreElements();){
                          ZipEntry entry = (ZipEntry)entries.nextElement();
                          file = new File(entry.getName());

                          if(entry.isDirectory()){
                              file.mkdirs();
                          }
                          else{
                              //如果指定文件的目錄不存在,則創(chuàng)建之.
                              File parent = file.getParentFile();
                              if(!parent.exists()){
                                  parent.mkdirs();
                              }

                              inputStream = zipFile.getInputStream(entry);

                              fileOut = new FileOutputStream(file);
                              while(( this.readedBytes = inputStream.read(this.buf) ) > 0){
                                  fileOut.write(this.buf , 0 , this.readedBytes );
                              }
                              fileOut.close();

                              inputStream.close();
                          }    
                      }
                      this.zipFile.close();
                  }catch(IOException ioe){
                      ioe.printStackTrace();
                  }
              }

              //設(shè)置緩沖區(qū)大小
              public void setBufSize(int bufSize){
                  this.bufSize = bufSize;
              }

              //測試AntZip類
              public static void main(String[] args)throws Exception{
                  if(args.length==2){
                      String name = args[1];
                      AntZip zip = new AntZip();

                      if(args[0].equals("-zip"))
                          zip.doZip(name);
                      else if(args[0].equals("-unzip"))
                          zip.unZip(name);
                  }
                  else{
                      System.out.println("Usage:");
                      System.out.println("壓縮:java AntZip -zip directoryName");
                      System.out.println("解壓:java AntZip -unzip fileName.zip");
                      throw new Exception("Arguments error!");
                  }
              }
          }

          posted @ 2012-01-03 17:32 AthrunWang 閱讀(1556) | 評論 (0)編輯 收藏
          java實現(xiàn)zip與unzip

          jdk提供了Zip相關(guān)的類方便的實現(xiàn)壓縮和解壓縮。使用方法很簡單。下邊分別是壓縮和解壓縮的簡單事例
          1,壓縮的
          import java.io.BufferedInputStream;
          import java.io.BufferedOutputStream;
          import java.io.File;
          import java.io.FileInputStream;
          import java.io.FileOutputStream;
          import java.util.zip.ZipEntry;
          import java.util.zip.ZipOutputStream;

          public class Zip {
              
          static final int BUFFER = 2048;

              
          public static void main(String argv[]) {
                  
          try {
                      BufferedInputStream origin 
          = null;
                      FileOutputStream dest 
          = new FileOutputStream("E:\\test\\myfiles.zip");
                      ZipOutputStream out 
          = new ZipOutputStream(new BufferedOutputStream(
                              dest));
                      
          byte data[] = new byte[BUFFER];
                      File f 
          = new File("e:\\test\\a\\");
                      File files[] 
          = f.listFiles();

                      
          for (int i = 0; i < files.length; i++{
                          FileInputStream fi 
          = new FileInputStream(files[i]);
                          origin 
          = new BufferedInputStream(fi, BUFFER);
                          ZipEntry entry 
          = new ZipEntry(files[i].getName());
                          out.putNextEntry(entry);
                          
          int count;
                          
          while ((count = origin.read(data, 0, BUFFER)) != -1{
                              out.write(data, 
          0, count);
                          }

                          origin.close();
                      }

                      out.close();
                  }
           catch (Exception e) {
                      e.printStackTrace();
                  }

              }

          }


          2,解壓縮的。
          import java.io.BufferedInputStream;
          import java.io.BufferedOutputStream;
          import java.io.File;
          import java.io.FileOutputStream;
          import java.util.Enumeration;
          import java.util.zip.ZipEntry;
          import java.util.zip.ZipFile;

          public class UnZip {
              
          static final int BUFFER = 2048;

              
          public static void main(String argv[]) {
                  
          try {
                      String fileName 
          = "E:\\test\\myfiles.zip";
                      String filePath 
          = "E:\\test\\";
                      ZipFile zipFile 
          = new ZipFile(fileName);
                      Enumeration emu 
          = zipFile.entries();
                      
          int i=0;
                      
          while(emu.hasMoreElements()){
                          ZipEntry entry 
          = (ZipEntry)emu.nextElement();
                          
          //會把目錄作為一個file讀出一次,所以只建立目錄就可以,之下的文件還會被迭代到。
                          if (entry.isDirectory())
                          
          {
                              
          new File(filePath + entry.getName()).mkdirs();
                              
          continue;
                          }

                          BufferedInputStream bis 
          = new BufferedInputStream(zipFile.getInputStream(entry));
                          File file 
          = new File(filePath + entry.getName());
                          
          //加入這個的原因是zipfile讀取文件是隨機讀取的,這就造成可能先讀取一個文件
                          
          //而這個文件所在的目錄還沒有出現(xiàn)過,所以要建出目錄來。
                          File parent = file.getParentFile();
                          
          if(parent != null && (!parent.exists())){
                              parent.mkdirs();
                          }

                          FileOutputStream fos 
          = new FileOutputStream(file);
                          BufferedOutputStream bos 
          = new BufferedOutputStream(fos,BUFFER);           
                          
                          
          int count;
                          
          byte data[] = new byte[BUFFER];
                          
          while ((count = bis.read(data, 0, BUFFER)) != -1)
                          
          {
                              bos.write(data, 
          0, count);
                          }

                          bos.flush();
                          bos.close();
                          bis.close();
                      }

                      zipFile.close();
                  }
           catch (Exception e) {
                      e.printStackTrace();
                  }

              }

          }

          posted @ 2012-01-03 17:31 AthrunWang 閱讀(202) | 評論 (0)編輯 收藏
          關(guān)于NIO對文件讀寫的簡單總結(jié)

          本篇主要介紹的是關(guān)于nio在文件讀寫方面的簡單應(yīng)用,具體底層實現(xiàn)原理,并未深究。

          新的輸入/輸出(NIO)庫是在JDK 1.4中引入的。它與原來的I/O庫最重要的區(qū)別是數(shù)據(jù)打包和傳輸?shù)姆绞降牟煌瓉淼?/span> I/O 的方式處理數(shù)據(jù),而 NIO 的方式處理數(shù)據(jù)。按塊處理數(shù)據(jù)比按(流式的)字節(jié)處理數(shù)據(jù)要快得多。但是面向塊的I/O缺少一些面向流的I/O所具有的優(yōu)雅性和簡單性。

          示例代碼:使用IONIO讀取一個文件中的內(nèi)容

           1import java.io.FileInputStream;
           2import java.io.IOException;
           3import java.nio.ByteBuffer;
           4import java.nio.channels.FileChannel;
           5
           6public class Test {           
           7    /**  
           8     * 使用IO讀取指定文件的前1024個字節(jié)的內(nèi)容。  
           9     * @param file 指定文件名稱。  
          10     * @throws java.io.IOException IO異常。  
          11     */
           
          12    public static void ioRead(String file) throws IOException{
          13        FileInputStream in = new FileInputStream(file);
          14        byte[] b = new byte[1024];
          15        in.read(b);
          16        System.out.println(new String(b));
          17        in.close();
          18    }

          19
          20    /**  
          21     * 使用NIO讀取指定文件的前1024個字節(jié)的內(nèi)容。  
          22     * @param file 指定文件名稱。  
          23     * @throws java.io.IOException IO異常。  
          24     */
           
          25    public static void nioRead(String file) throws IOException{
          26        FileInputStream in = new FileInputStream(file);
          27        FileChannel channel = in.getChannel();
          28
          29        ByteBuffer buffer = ByteBuffer.allocate(1024);
          30        channel.read(buffer);
          31        byte[] b = buffer.array();
          32        System.out.println(new String(b));
          33        channel.close();
          34    }

          35}

          從以上示例代碼中,我們可以看到對于nio非常重要的兩個核心概念:通道與緩沖區(qū)。

          1)通道
               Channel是對原I/O包中的流的模擬,可以通過它讀取和寫入數(shù)據(jù)。拿NIO與原來的I/O做個比較,通道就像是流。
             通道與流的不同之處在于通道是雙向的。而流只是在一個方向上移動(一個流必須是InputStream或者OutputStream的子類) 而通道可以用于讀、寫或者同時用于讀寫。
               因為它們是雙向的,所以通道可以比流更好地反映底層操作系統(tǒng)的真實情況。特別是在UNIX模型中,底層操作系統(tǒng)通道是雙向的。

          2)緩沖區(qū)
                 NIO庫中,所有數(shù)據(jù)都是用緩沖區(qū)處理的。在讀取數(shù)據(jù)時,它是直接讀到緩沖區(qū)中的。在寫入數(shù)據(jù)時,它是寫入到緩沖區(qū)中的。任何時候訪問NIO中的數(shù)據(jù),您都是將它放到緩沖區(qū)中。
             緩沖區(qū)實質(zhì)上是一個數(shù)組。通常它是一個字節(jié)數(shù)組,但是也可以使用其他種類的數(shù)組。但是一個緩沖區(qū)不僅僅是一個數(shù)組。緩沖區(qū)提供了對數(shù)據(jù)的結(jié)構(gòu)化訪問,而且還可以跟蹤系統(tǒng)的讀/寫進程。
             最常用的緩沖區(qū)類型是ByteBuffer 一個ByteBuffer可以在其底層字節(jié)數(shù)組上進行get/set操作(即字節(jié)的獲取和設(shè)置)
             ByteBuffer不是NIO中唯一的緩沖區(qū)類型。事實上,對于每一種基本Java類型都有一種緩沖區(qū)類型:
             ByteBuffer
             CharBuffer
             ShortBuffer

             IntBuffer
             LongBuffer
             FloatBuffer
             DoubleBuffer
             每一個Buffer類都是Buffer接口的一個實例。 

          文件的讀寫

          nio讀取文件涉及三個步驟:
             (1) FileInputStream獲取Channel
             (2) 創(chuàng)建Buffer
             (3) 將數(shù)據(jù)從Channel讀到Buffer 中。

          文件的寫操作與讀操作類似。

          下面我以文件的拷貝為例,展示一下nio的讀寫過程:

           1import java.io.FileInputStream;
           2import java.io.FileNotFoundException;
           3import java.io.FileOutputStream;
           4import java.io.IOException;
           5import java.nio.ByteBuffer;
           6import java.nio.channels.FileChannel;
           7
           8/**
           9 * 將一個文件的所有內(nèi)容拷貝到另一個文件中。
          10 * 
          11 * 基本步驟:
          12 * 1.得到輸入輸出通道,創(chuàng)建緩沖區(qū)
          13 * 2.從源文件中將數(shù)據(jù)讀到這個緩沖區(qū)中,然后將緩沖區(qū)寫入目標文件.此過程需不斷循環(huán)直到源文件結(jié)束
          14 * 
          15 * @author greatjone
          16 */

          17public class CopyFile {
          18    public static void copy(String file,String copyfile) throws IOException{
          19         // 獲取源文件和目標文件的輸入輸出流
          20        FileInputStream fin = new FileInputStream(file);
          21        FileOutputStream fout = new FileOutputStream(copyfile);
          22
          23        // 獲取輸入輸出通道
          24        FileChannel fcin = fin.getChannel();
          25        FileChannel fcout = fout.getChannel();
          26
          27        // 創(chuàng)建緩沖區(qū)
          28        ByteBuffer buffer = ByteBuffer.allocate(1024);
          29
          30        while (true{
          31            // clear方法重設(shè)緩沖區(qū),使它可以接受讀入的數(shù)據(jù)
          32            buffer.clear();
          33
          34            // 從輸入通道中將數(shù)據(jù)讀到緩沖區(qū)
          35            int r = fcin.read(buffer);
          36
          37            // read方法返回讀取的字節(jié)數(shù),可能為零,如果該通道已到達流的末尾,則返回-1
          38            if (r == -1{
          39                break;
          40            }

          41            
          42            // flip方法讓緩沖區(qū)可以將新讀入的數(shù)據(jù)寫入另一個通道
          43            buffer.flip();
          44
          45            // 從輸出通道中將數(shù)據(jù)寫入緩沖區(qū)
          46            fcout.write(buffer);
          47        }

          48    }

          49}

          50

           關(guān)于nio更加詳細深入研究請參考:http://zhangshixi.javaeye.com/category/101360

          posted @ 2012-01-03 17:28 AthrunWang 閱讀(389) | 評論 (0)編輯 收藏
          Java 下載支持斷點續(xù)傳

          [代碼] [Java]代碼,服務(wù)器端實現(xiàn)

          File file = new File(location);                        
                                  if (file.exists()) {                                        
                                      long p = 0;
                                      long fileLength;
                                      fileLength = file.length();
                                      
                                      // get file content
                                      InputStream ins = new FileInputStream(file);
                                      bis = new BufferedInputStream(ins);                            
                                      
                                      // tell the client to allow accept-ranges
                                      response.reset();
                                      response.setHeader("Accept-Ranges", "bytes");
                                      
                                      // client requests a file block download start byte
                                      if (request.getHeader("Range") != null) {                                
                                          response.setStatus(javax.servlet.http.HttpServletResponse.SC_PARTIAL_CONTENT);
                                          p = Long.parseLong(request.getHeader("Range")
                                                  .replaceAll("bytes=", "")
                                                  .replaceAll("-", "")
                                                  );                                
                                      }
                                      // support multi-threaded download
                                      // respone format:
                                      // Content-Length:[file size] - [client request start bytes from file block]
                                      response.setHeader("Content-Length", new Long(fileLength - p).toString());
                                      
                                      if (p != 0) {
                                          // 斷點開始
                                          // 響應(yīng)的格式是:
                                          // Content-Range: bytes [文件塊的開始字節(jié)]-[文件的總大小 - 1]/[文件的總大小]
                                          String contentRange = new StringBuffer("bytes ")
                                                  .append(new Long(p).toString())
                                                  .append("-")
                                                  .append(new Long(fileLength - 1).toString())
                                                  .append("/")
                                                  .append(new Long(fileLength).toString())
                                                  .toString();
                                          response.setHeader("Content-Range", contentRange);
                                          // pointer move to seek
                                          bis.skip(p);
                                      }
                                      
                                      String fileName = file.getName();
                                      response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
                                                   
                                      while ((size = bis.read(buf)) != -1) {
                                          response.getOutputStream().write(buf,0,size);
                                          response.getOutputStream().flush();                                
                                      }
                                      bis.close();

          [代碼] 客戶端下載測試

          public class TestDownload {

              /**
               * @param args
               */
              public static void main(String[] args) {
                  // TODO Auto-generated method stub
                  HttpURLConnection httpURLConnection = null;
                  URL url = null;
                  BufferedInputStream bis = null;
                  byte[] buf = new byte[10240];
                  int size = 0;
                  String fileName = "aaa.zip";
                  String filePath = "C:\\Users\\Desktop";
                  String remoteUrl = "http://127.0.0.1:8080/down.zip";

                  // 檢查本地文件
                  RandomAccessFile rndFile = null;
                  File file = new File(filePath + "\\" + fileName);
                  long remoteFileSize = getRemoteFileSzie(remoteUrl);
                  long nPos = 0;
                 
                  if (file.exists()) {                       
                      long localFileSzie = file.length();
                      if (localFileSzie < remoteFileSize) {                   
                          System.out.println("文件續(xù)傳...");
                          nPos = localFileSzie;
                      } else {
                          System.out.println("文件存在,重新下載...");
                          file.delete();
                          try {
                              file.createNewFile();
                          } catch (Exception e) {
                              // TODO: handle exception
                              e.printStackTrace();
                          }   
                      }
                     
                  } else {
                      // 建立文件
                      try {
                          file.createNewFile();
                      } catch (Exception e) {
                          // TODO: handle exception
                          e.printStackTrace();
                      }           
                  }
                 
                  // 下載文件
                  try {
                      url = new URL(remoteUrl);       
                      httpURLConnection = (HttpURLConnection)url.openConnection();
                      // 設(shè)置User-Agent
                      httpURLConnection.setRequestProperty("User-Agent", "Net");
                      // 設(shè)置續(xù)傳開始
                      httpURLConnection.setRequestProperty("Range", "bytes=" + nPos + "-");
                      // 獲取輸入流
                      bis = new BufferedInputStream(httpURLConnection.getInputStream());           
                      rndFile = new RandomAccessFile(filePath + "\\" + fileName, "rw");
                      rndFile.seek(nPos);
                      int i = 0;
                      while ((size = bis.read(buf)) != -1) {
                          //if (i > 500) break;               
                          rndFile.write(buf, 0, size);
                         
                          i++;
                      }
                      System.out.println("i=" + i);
                      httpURLConnection.disconnect();
                  } catch (Exception e) {
                      // TODO: handle exception
                      e.printStackTrace();
                  }
              }

              public static long getRemoteFileSzie(String url) {
                  long size = 0;
                  try {
                      HttpURLConnection httpUrl = (HttpURLConnection)(new URL(url)).openConnection();
                      size = httpUrl.getContentLength();
                      httpUrl.disconnect();           
                  } catch (Exception e) {
                      // TODO: handle exception
                      e.printStackTrace();
                  }
                  return size;
              }
          }

          posted @ 2012-01-02 17:31 AthrunWang 閱讀(462) | 評論 (0)編輯 收藏
          Java實現(xiàn)文件的復制和新Nio包通道的運用--Thinking in java

          首先是二進制讀取文件成為字節(jié)的代碼

            

          1. package com.bird.thinking;  
          2.   
          3. import java.io.BufferedInputStream;  
          4. import java.io.File;  
          5. import java.io.FileInputStream;  
          6. import java.io.FileNotFoundException;  
          7. import java.io.IOException;  
          8.   
          9. /** 
          10.  * @use 讀取二進制文件 
          11.  * @author Bird 
          12.  * 
          13.  */  
          14. public class BinaryFile {  
          15.     public static byte[] read(File bFile) throws FileNotFoundException{  
          16.         BufferedInputStream bf = new BufferedInputStream(new FileInputStream(bFile));//構(gòu)建讀取流  
          17.         try{  
          18.             byte[] data = new byte[bf.available()];//構(gòu)建緩沖區(qū)  
          19.             bf.read(data);  
          20.             return data;  
          21.         } catch (IOException e) {  
          22.             throw new RuntimeException(e);//改變成運行時異常  
          23.         }finally{  
          24.             try {  
          25.                 bf.close();  
          26.             } catch (IOException e) {  
          27.                 throw new RuntimeException(e);  
          28.             }  
          29.         }  
          30.           
          31.     }  
          32.       
          33.       
          34.     public static byte[] read(String bFile) throws FileNotFoundException{//重載構(gòu)造方法  
          35.         return read(new File(bFile).getAbsoluteFile());  
          36.     }  
          37.       
          38.     public static void main(String [] args) throws FileNotFoundException{  
          39.         for(byte a: read("d://book.xml"))  
          40.             System.out.print(a);  
          41.     }  
          42. }  



          下面是包裝JAVA的控制臺輸入實現(xiàn)回顯功能

          1. package com.bird.thinking;  
          2.   
          3. import java.io.BufferedReader;  
          4. import java.io.IOException;  
          5. import java.io.InputStreamReader;  
          6.   
          7. /** 
          8.  * @use 從控制臺輸入并且回顯 
          9.  * @author Bird 
          10.  * 
          11.  */  
          12. public class Echo {  
          13.     public static void main(String [] args) throws IOException{  
          14.         BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));//將輸入流包裝成BufferedReader  
          15.         String s = null;  
          16.         while((s = stdin.readLine()) != null && s.length() !=0){  
          17.             System.out.println(s);  
          18.             if(s.equals("exit"))  
          19.                 break;  
          20.         }  
          21.     }  
          22. }  



          下面是使用NIO包的通道功能讀取并且寫入文件,并在文件的末尾追加內(nèi)容

          1. package com.bird.thinking;  
          2.   
          3. import java.io.FileOutputStream;  
          4. import java.io.RandomAccessFile;  
          5. import java.nio.ByteBuffer;  
          6. import java.nio.channels.FileChannel;  
          7.   
          8. /** 
          9.  * @use 新nio包的通道讀取文件 
          10.  * @author Bird 
          11.  * 
          12.  */  
          13. public class GetChannel {  
          14.       
          15.     public static void main(String [] args) throws Exception{  
          16.         FileChannel fc = new FileOutputStream("d://bird.txt").getChannel();//建立讀取通道  
          17.         fc.write(ByteBuffer.wrap(BinaryFile.read("d://book.xml")));//獲得字節(jié)流并且通過通道寫入  
          18.         fc.close();  
          19.           
          20.         Thread.sleep(500);//等待磁盤寫入數(shù)據(jù)完畢  
          21.           
          22.         fc = new RandomAccessFile("d://bird.txt","rw").getChannel();//隨機讀取,對文件末尾追加內(nèi)容  
          23.         fc.position(fc.size());//調(diào)整文件指針的位置到文件的末尾  
          24.         fc.write(ByteBuffer.wrap("哥再加一點".getBytes()));//在文件末尾加入這幾個字  
          25.         fc.close();       
          26.     }  
          27.       
          28.   
          29. }  



          下面是對文件的復制

          1. package com.bird.thinking;  
          2.   
          3. import java.io.FileInputStream;  
          4. import java.io.FileOutputStream;  
          5. import java.io.IOException;  
          6. import java.nio.ByteBuffer;  
          7. import java.nio.channels.FileChannel;  
          8.   
          9. /** 
          10.  *  
          11.  * @author Bird 
          12.  * @use 文件的復制 
          13.  */  
          14. public class ChannelCopy {  
          15.     private static final int BSIZE = 1024;//文件緩沖字節(jié)區(qū),大小可以自己定  
          16.     public static void main(String [] args) throws IOException{  
          17.         FileChannel in = new FileInputStream("d://book.xml").getChannel();//得到輸入通道  
          18.         FileChannel out = new FileOutputStream("d://bird.xml").getChannel();//得到輸出通道  
          19.         ByteBuffer buffer = ByteBuffer.allocate(BSIZE);//設(shè)定緩沖區(qū)  
          20.         while(in.read(buffer) != -1){  
          21.             buffer.flip();//準備寫入,防止其他讀取,鎖住文件  
          22.             out.write(buffer);  
          23.             buffer.clear();//準備讀取。將緩沖區(qū)清理完畢,移動文件內(nèi)部指針  
          24.         }  
          25.     }  

          posted @ 2012-01-02 14:19 AthrunWang 閱讀(599) | 評論 (0)編輯 收藏
          主題:JAVA NIO 簡介

          1.   基本 概念

          IO 是主存和外部設(shè)備 ( 硬盤、終端和網(wǎng)絡(luò)等 ) 拷貝數(shù)據(jù)的過程。 IO 是操作系統(tǒng)的底層功能實現(xiàn),底層通過 I/O 指令進行完成。

          所有語言運行時系統(tǒng)提供執(zhí)行 I/O 較高級別的工具。 (c printf scanf,java 的面向?qū)ο蠓庋b )

          2.    Java 標準 io 回顧

          Java 標準 IO 類庫是 io 面向?qū)ο蟮囊环N抽象。基于本地方法的底層實現(xiàn),我們無須關(guān)注底層實現(xiàn)。 InputStream\OutputStream( 字節(jié)流 ) :一次傳送一個字節(jié)。 Reader\Writer( 字符流 ) :一次一個字符。

          3.    nio 簡介

          nio java New IO 的簡稱,在 jdk1.4 里提供的新 api Sun 官方標榜的特性如下:

              為所有的原始類型提供 (Buffer) 緩存支持。

              字符集編碼解碼解決方案。

              Channel :一個新的原始 I/O 抽象。

              支持鎖和內(nèi)存映射文件的文件訪問接口。

              提供多路 (non-bloking) 非阻塞式的高伸縮性網(wǎng)絡(luò) I/O

          本文將圍繞這幾個特性進行學習和介紹。

          4.   Buffer&Chanel

          Channel buffer NIO 是兩個最基本的數(shù)據(jù)類型抽象。

          Buffer:

                 是一塊連續(xù)的內(nèi)存塊。

                 NIO 數(shù)據(jù)讀或?qū)懙闹修D(zhuǎn)地。

          Channel:

                 數(shù)據(jù)的源頭或者數(shù)據(jù)的目的地

                 用于向 buffer 提供數(shù)據(jù)或者讀取 buffer 數(shù)據(jù) ,buffer 對象的唯一接口。

                  異步 I/O 支持


          圖1:channel和buffer關(guān)系
           

           

          例子 1:CopyFile.java:

          Java代碼  收藏代碼
          1. package sample;  
          2.   
          3. import java.io.FileInputStream;  
          4. import java.io.FileOutputStream;  
          5. import java.nio.ByteBuffer;  
          6. import java.nio.channels.FileChannel;  
          7.   
          8. public class CopyFile {  
          9.     public static void main(String[] args) throws Exception {  
          10.         String infile = "C:\\copy.sql";  
          11.         String outfile = "C:\\copy.txt";  
          12.         // 獲取源文件和目標文件的輸入輸出流  
          13.         FileInputStream fin = new FileInputStream(infile);  
          14.         FileOutputStream fout = new FileOutputStream(outfile);  
          15.         // 獲取輸入輸出通道  
          16.         FileChannel fcin = fin.getChannel();  
          17.         FileChannel fcout = fout.getChannel();  
          18.         // 創(chuàng)建緩沖區(qū)  
          19.         ByteBuffer buffer = ByteBuffer.allocate(1024);  
          20.         while (true) {  
          21.             // clear方法重設(shè)緩沖區(qū),使它可以接受讀入的數(shù)據(jù)  
          22.             buffer.clear();  
          23.             // 從輸入通道中將數(shù)據(jù)讀到緩沖區(qū)  
          24.             int r = fcin.read(buffer);  
          25.             // read方法返回讀取的字節(jié)數(shù),可能為零,如果該通道已到達流的末尾,則返回-1  
          26.             if (r == -1) {  
          27.                 break;  
          28.             }  
          29.             // flip方法讓緩沖區(qū)可以將新讀入的數(shù)據(jù)寫入另一個通道  
          30.             buffer.flip();  
          31.             // 從輸出通道中將數(shù)據(jù)寫入緩沖區(qū)  
          32.             fcout.write(buffer);  
          33.         }  
          34.     }  
          35. }  

           

          其中 buffer 內(nèi)部結(jié)構(gòu)如下 ( 下圖拷貝自資料 ):


          圖2:buffer內(nèi)部結(jié)構(gòu) 

          一個 buffer 主要由 position,limit,capacity 三個變量來控制讀寫的過程。此三個變量的含義見如下表格:

          參數(shù)

          寫模式    

          讀模式

          position

          當前寫入的單位數(shù)據(jù)數(shù)量。

          當前讀取的單位數(shù)據(jù)位置。

          limit

          代表最多能寫多少單位數(shù)據(jù)和容量是一樣的。

          代表最多能讀多少單位數(shù)據(jù),和之前寫入的單位數(shù)據(jù)量一致。

          capacity

          buffer 容量

          buffer 容量

          Buffer 常見方法:

          flip(): 寫模式轉(zhuǎn)換成讀模式

          rewind() :將 position 重置為 0 ,一般用于重復讀。

          clear() :清空 buffer ,準備再次被寫入 (position 變成 0 limit 變成 capacity)

          compact(): 將未讀取的數(shù)據(jù)拷貝到 buffer 的頭部位。

          mark() reset():mark 可以標記一個位置, reset 可以重置到該位置。

          Buffer 常見類型: ByteBuffer MappedByteBuffer CharBuffer DoubleBuffer FloatBuffer IntBuffer LongBuffer ShortBuffer

          channel 常見類型 :FileChannel DatagramChannel(UDP) SocketChannel(TCP) ServerSocketChannel(TCP)

          在本機上面做了個簡單的性能測試。我的筆記本性能一般。 ( 具體代碼可以見附件。見 nio.sample.filecopy 包下面的例子 ) 以下是參考數(shù)據(jù):

                 場景 1 Copy 一個 370M 的文件

                 場景 2: 三個線程同時拷貝,每個線程拷貝一個 370M 文件

           

          場景

          FileInputStream+

          FileOutputStream

          FileInputStream+

          BufferedInputStream+

          FileOutputStream

          ByteBuffer+

          FileChannel

          MappedByteBuffer

          +FileChannel

          場景一時間 ( 毫秒 )                 

          25155

          17500

          19000

          16500

          場景二時間 ( 毫秒 )

          69000

          67031

          74031

          71016

          5.    nio.charset

          字符編碼解碼 : 字節(jié)碼本身只是一些數(shù)字,放到正確的上下文中被正確被解析。向 ByteBuffer 中存放數(shù)據(jù)時需要考慮字符集的編碼方式,讀取展示 ByteBuffer 數(shù)據(jù)時涉及對字符集解碼。

          Java.nio.charset 提供了編碼解碼一套解決方案。

          以我們最常見的 http 請求為例,在請求的時候必須對請求進行正確的編碼。在得到響應(yīng)時必須對響應(yīng)進行正確的解碼。

          以下代碼向 baidu 發(fā)一次請求,并獲取結(jié)果進行顯示。例子演示到了 charset 的使用。

          例子 2BaiduReader.java

          Java代碼  收藏代碼
          1. package nio.readpage;  
          2.   
          3. import java.nio.ByteBuffer;  
          4. import java.nio.channels.SocketChannel;  
          5. import java.nio.charset.Charset;  
          6. import java.net.InetSocketAddress;  
          7. import java.io.IOException;  
          8. public class BaiduReader {  
          9.     private Charset charset = Charset.forName("GBK");// 創(chuàng)建GBK字符集  
          10.     private SocketChannel channel;  
          11.     public void readHTMLContent() {  
          12.         try {  
          13.             InetSocketAddress socketAddress = new InetSocketAddress(  
          14. "www.baidu.com", 80);  
          15. //step1:打開連接  
          16.             channel = SocketChannel.open(socketAddress);  
          17.         //step2:發(fā)送請求,使用GBK編碼  
          18.             channel.write(charset.encode("GET " + "/ HTTP/1.1" + "\r\n\r\n"));  
          19.             //step3:讀取數(shù)據(jù)  
          20.             ByteBuffer buffer = ByteBuffer.allocate(1024);// 創(chuàng)建1024字節(jié)的緩沖  
          21.             while (channel.read(buffer) != -1) {  
          22.                 buffer.flip();// flip方法在讀緩沖區(qū)字節(jié)操作之前調(diào)用。  
          23.                 System.out.println(charset.decode(buffer));  
          24.                 // 使用Charset.decode方法將字節(jié)轉(zhuǎn)換為字符串  
          25.                 buffer.clear();// 清空緩沖  
          26.             }  
          27.         } catch (IOException e) {  
          28.             System.err.println(e.toString());  
          29.         } finally {  
          30.             if (channel != null) {  
          31.                 try {  
          32.                     channel.close();  
          33.                 } catch (IOException e) {  
          34.                 }  
          35.             }  
          36.         }  
          37.     }  
          38.     public static void main(String[] args) {  
          39.         new BaiduReader().readHTMLContent();  
          40.     }  
          41. }  
           

          6.      非阻塞 IO

          關(guān)于非阻塞 IO 將從何為阻塞、何為非阻塞、非阻塞原理和異步核心 API 幾個方面來理解。

          何為阻塞?

          一個常見的網(wǎng)絡(luò) IO 通訊流程如下 :



           

          圖3:網(wǎng)絡(luò)通訊基本過程

          從該網(wǎng)絡(luò)通訊過程來理解一下何為阻塞 :

          在以上過程中若連接還沒到來,那么 accept 會阻塞 , 程序運行到這里不得不掛起, CPU 轉(zhuǎn)而執(zhí)行其他線程。

          在以上過程中若數(shù)據(jù)還沒準備好, read 會一樣也會阻塞。

          阻塞式網(wǎng)絡(luò) IO 的特點:多線程處理多個連接。每個線程擁有自己的棧空間并且占用一些 CPU 時間。每個線程遇到外部為準備好的時候,都會阻塞掉。阻塞的結(jié)果就是會帶來大量的進程上下文切換。且大部分進程上下文切換可能是無意義的。比如假設(shè)一個線程監(jiān)聽一個端口,一天只會有幾次請求進來,但是該 cpu 不得不為該線程不斷做上下文切換嘗試,大部分的切換以阻塞告終。

           

          何為非阻塞?

          下面有個隱喻:

          一輛從 A 開往 B 的公共汽車上,路上有很多點可能會有人下車。司機不知道哪些點會有哪些人會下車,對于需要下車的人,如何處理更好?

          1. 司機過程中定時詢問每個乘客是否到達目的地,若有人說到了,那么司機停車,乘客下車。 ( 類似阻塞式 )

          2. 每個人告訴售票員自己的目的地,然后睡覺,司機只和售票員交互,到了某個點由售票員通知乘客下車。 ( 類似非阻塞 )

          很顯然,每個人要到達某個目的地可以認為是一個線程,司機可以認為是 CPU 。在阻塞式里面,每個線程需要不斷的輪詢,上下文切換,以達到找到目的地的結(jié)果。而在非阻塞方式里,每個乘客 ( 線程 ) 都在睡覺 ( 休眠 ) ,只在真正外部環(huán)境準備好了才喚醒,這樣的喚醒肯定不會阻塞。

            非阻塞的原理

          把整個過程切換成小的任務(wù),通過任務(wù)間協(xié)作完成。

          由一個專門的線程來處理所有的 IO 事件,并負責分發(fā)。

          事件驅(qū)動機制:事件到的時候觸發(fā),而不是同步的去監(jiān)視事件。

          線程通訊:線程之間通過 wait,notify 等方式通訊。保證每次上下文切換都是有意義的。減少無謂的進程切換。

          以下是異步 IO 的結(jié)構(gòu):



           

          圖4:非阻塞基本原理

           

          Reactor 就是上面隱喻的售票員角色。每個線程的處理流程大概都是讀取數(shù)據(jù)、解碼、計算處理、編碼、發(fā)送響應(yīng)。

          異步 IO 核心 API

          Selector

          異步 IO 的核心類,它能檢測一個或多個通道 (channel) 上的事件,并將事件分發(fā)出去。

          使用一個 select 線程就能監(jiān)聽多個通道上的事件,并基于事件驅(qū)動觸發(fā)相應(yīng)的響應(yīng)。而不需要為每個 channel 去分配一個線程。

          SelectionKey

          包含了事件的狀態(tài)信息和時間對應(yīng)的通道的綁定。

          例子 1 單線程實現(xiàn)監(jiān)聽兩個端口。 ( nio.asyn 包下面的例子。 )

          例子 2 NIO 線程協(xié)作實現(xiàn)資源合理利用。 (wait,notify) ( nio.asyn.multithread 下的例子 )

          posted @ 2012-01-02 13:33 AthrunWang 閱讀(202) | 評論 (0)編輯 收藏
          簡單的基于xfire框架發(fā)布webserivce服務(wù)

          前段時間在弄各種框架下的webservice,要弄demo,網(wǎng)上搜羅了許多,都講得很好,但感覺就是說得很多很復雜,我就想弄個服務(wù)出來供我用一下, 要像網(wǎng)上那么做覺著太麻煩,后來參考各路神仙大佬們后,把代碼極度縮小,寫了個小實例供自個跑著玩,順便代碼貼上,供大伙口水
          支持包:xfire框架lib下核心包,自己官網(wǎng)上下去,在這里就不貼了,除此之外有java環(huán)境1.6+就Ok了,其它略過,上代碼了。
          package com.tyky.test.bean;

          public class Employee{
              
              private String id;
              
              private String name;
              
              public String getId() {
                  return id;
              }

              public void setId(String id) {
                  this.id = id;
              }

              public String getName() {
                  return name;
              }

              public void setName(String name) {
                  this.name = name;
              }

              public String getAddress() {
                  return address;
              }

              public void setAddress(String address) {
                  this.address = address;
              }

              private String address;
              
              
          }
          package com.tyky.service;

          import com.tyky.test.bean.Employee;

          public interface EmployeeService {

              public boolean addEmployee(Employee e);
              
              public boolean deleteEmployee(String id);
              
              public Employee getEmployee(String id);
              
          }
          package com.tyky.serviceImpl;

          import com.tyky.service.EmployeeService;
          import com.tyky.test.bean.Employee;

          public class EmployeeServiceImpl implements EmployeeService {

              @Override
              public boolean addEmployee(Employee e) {
                  //業(yè)務(wù)想咋整自已實現(xiàn)去吧,我這里作例子,就直接回true了,呵呵
                  return false;
              }

              @Override
              public boolean deleteEmployee(String id) {
                  //業(yè)務(wù)想咋整自已實現(xiàn)去吧,我這里作例子,就直接回true了,呵呵
                  return false;
              }

              @Override
              public Employee getEmployee(String id) {
                  //業(yè)務(wù)想咋整自已實現(xiàn)去吧,我這里作例子,就直接回true了,呵呵
                  Employee e = new Employee();
                  e.setAddress("http://業(yè)務(wù)想咋整自已實現(xiàn)去吧,我這里作例子,就直接回true了,呵呵");
                  e.setId("http://業(yè)務(wù)想咋整自已實現(xiàn)去吧,我這里作例子,就直接回true了,呵呵");
                  e.setName("http://業(yè)務(wù)想咋整自已實現(xiàn)去吧,我這里作例子,就直接回true了,呵呵");
                  return e;
              }

              
          }
          //現(xiàn)在src下建個xfire文件夾,新建個service.xml文件
          <?xml version="1.0" encoding="UTF-8"?>
          <beans xmlns="http://xfire.codehaus.org/config/1.0">

              <service>
                  <name>EmployeeService</name>
                  <serviceClass>com.tyky.service.EmployeeService</serviceClass>
                  <implementationClass>
                      com.tyky.serviceImpl.EmployeeServiceImpl
                  </implementationClass>
                  <style>document</style>
              </service>
          </beans>
          <?xml version="1.0" encoding="UTF-8"?>
          <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
            <servlet>
              <servlet-name>XFireServlet</servlet-name>
              <servlet-class>org.codehaus.xfire.transport.http.XFireConfigurableServlet</servlet-class>
              <load-on-startup>0</load-on-startup>
            </servlet>
            <servlet-mapping>
              <servlet-name>XFireServlet</servlet-name>
              <url-pattern>/services/*</url-pattern>
            </servlet-mapping>
            <welcome-file-list>
              <welcome-file>index.jsp</welcome-file>
            </welcome-file-list>
          </web-app>
          //現(xiàn)在工程完成,可以把容器集成到eclipse里跑,也可以打war包再跑,隨便你選擇一個跑開即行了,訪問http://localhost:8080/employeeServiceForXfire/services/EmployeeService?wsdl
          <?xml version="1.0" encoding="UTF-8" ?>
          - <wsdl:definitions targetNamespace="http://service.tyky.com" xmlns:ns1="http://bean.test.tyky.com" xmlns:soapenc12="http://www.w3.org/2003/05/soap-encoding" xmlns:tns="http://service.tyky.com" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap11="http://schemas.xmlsoap.org/soap/envelope/" xmlns:wsdlsoap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:soapenc11="http://schemas.xmlsoap.org/soap/encoding/" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">
          - <wsdl:types>
          - <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" attributeFormDefault="qualified" elementFormDefault="qualified" targetNamespace="http://service.tyky.com">
            <xsd:element name="getEmployeein0" type="xsd:string" />
            <xsd:element name="getEmployeeout" type="ns1:Employee" />
            <xsd:element name="addEmployeein0" type="ns1:Employee" />
            <xsd:element name="addEmployeeout" type="xsd:boolean" />
            <xsd:element name="deleteEmployeein0" type="xsd:string" />
            <xsd:element name="deleteEmployeeout" type="xsd:boolean" />
            </xsd:schema>
          - <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" attributeFormDefault="qualified" elementFormDefault="qualified" targetNamespace="http://bean.test.tyky.com">
          - <xsd:complexType name="Employee">
          - <xsd:sequence>
            <xsd:element minOccurs="0" name="address" nillable="true" type="xsd:string" />
            <xsd:element minOccurs="0" name="id" nillable="true" type="xsd:string" />
            <xsd:element minOccurs="0" name="name" nillable="true" type="xsd:string" />
            </xsd:sequence>
            </xsd:complexType>
            </xsd:schema>
            </wsdl:types>
          - <wsdl:message name="getEmployeeResponse">
            <wsdl:part name="getEmployeeout" element="tns:getEmployeeout" />
            </wsdl:message>
          - <wsdl:message name="deleteEmployeeRequest">
            <wsdl:part name="deleteEmployeein0" element="tns:deleteEmployeein0" />
            </wsdl:message>
          - <wsdl:message name="addEmployeeResponse">
            <wsdl:part name="addEmployeeout" element="tns:addEmployeeout" />
            </wsdl:message>
          - <wsdl:message name="getEmployeeRequest">
            <wsdl:part name="getEmployeein0" element="tns:getEmployeein0" />
            </wsdl:message>
          - <wsdl:message name="addEmployeeRequest">
            <wsdl:part name="addEmployeein0" element="tns:addEmployeein0" />
            </wsdl:message>
          - <wsdl:message name="deleteEmployeeResponse">
            <wsdl:part name="deleteEmployeeout" element="tns:deleteEmployeeout" />
            </wsdl:message>
          - <wsdl:portType name="EmployeeServicePortType">
          - <wsdl:operation name="getEmployee">
            <wsdl:input name="getEmployeeRequest" message="tns:getEmployeeRequest" />
            <wsdl:output name="getEmployeeResponse" message="tns:getEmployeeResponse" />
            </wsdl:operation>
          - <wsdl:operation name="addEmployee">
            <wsdl:input name="addEmployeeRequest" message="tns:addEmployeeRequest" />
            <wsdl:output name="addEmployeeResponse" message="tns:addEmployeeResponse" />
            </wsdl:operation>
          - <wsdl:operation name="deleteEmployee">
            <wsdl:input name="deleteEmployeeRequest" message="tns:deleteEmployeeRequest" />
            <wsdl:output name="deleteEmployeeResponse" message="tns:deleteEmployeeResponse" />
            </wsdl:operation>
            </wsdl:portType>
          - <wsdl:binding name="EmployeeServiceHttpBinding" type="tns:EmployeeServicePortType">
            <wsdlsoap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http" />
          - <wsdl:operation name="getEmployee">
            <wsdlsoap:operation soapAction="" />
          - <wsdl:input name="getEmployeeRequest">
            <wsdlsoap:body use="literal" />
            </wsdl:input>
          - <wsdl:output name="getEmployeeResponse">
            <wsdlsoap:body use="literal" />
            </wsdl:output>
            </wsdl:operation>
          - <wsdl:operation name="addEmployee">
            <wsdlsoap:operation soapAction="" />
          - <wsdl:input name="addEmployeeRequest">
            <wsdlsoap:body use="literal" />
            </wsdl:input>
          - <wsdl:output name="addEmployeeResponse">
            <wsdlsoap:body use="literal" />
            </wsdl:output>
            </wsdl:operation>
          - <wsdl:operation name="deleteEmployee">
            <wsdlsoap:operation soapAction="" />
          - <wsdl:input name="deleteEmployeeRequest">
            <wsdlsoap:body use="literal" />
            </wsdl:input>
          - <wsdl:output name="deleteEmployeeResponse">
            <wsdlsoap:body use="literal" />
            </wsdl:output>
            </wsdl:operation>
            </wsdl:binding>
          - <wsdl:service name="EmployeeService">
          - <wsdl:port name="EmployeeServiceHttpPort" binding="tns:EmployeeServiceHttpBinding">
            <wsdlsoap:address location="http://192.9.11.53:8080/employeeServiceForXfire/services/EmployeeService" />
            </wsdl:port>
            </wsdl:service>
            </wsdl:definitions>

          posted @ 2011-12-28 20:56 AthrunWang 閱讀(330) | 評論 (0)編輯 收藏
          簡單的基于CXF框架發(fā)布webserivce服務(wù)

          前段時間在弄各種框架下的webservice,要弄demo,網(wǎng)上搜羅了許多,都講得很好,但感覺就是說得很多很復雜,我就想弄個服務(wù)出來供我用一下, 要像網(wǎng)上那么做覺著太麻煩,后來參考各路神仙大佬們后,把代碼極度縮小,寫了個小實例供自個跑著玩,順便代碼貼上,供大伙口水
          支持包:cxf框架lib下核心包,自己官網(wǎng)上下去,在這里就不貼了,除此之外有java環(huán)境1.6+就Ok了,其它略過,上代碼了。
          package com.cxf.bean;

          public class Employee {
              private String id;
              private String name;
              private String address;

              public String getId() {
                  return id;
              }

              public void setId(String id) {
                  this.id = id;
              }

              public String getName() {
                  return name;
              }

              public void setName(String name) {
                  this.name = name;
              }

              public String getAddress() {
                  return address;
              }

              public void setAddress(String address) {
                  this.address = address;
              }

          }
          package com.cxf.service;

          import javax.jws.WebService;

          import com.cxf.bean.Employee;

          @WebService
          public interface EmployeeService {
              public boolean insertEmployee(Employee e);

              public boolean updateEmployee(String id);

              public boolean deleteEmployee(String id);

              public Employee seletctEmployee(String id);
          }
          package com.cxf.service;

          import javax.jws.WebService;

          import com.cxf.bean.Employee;

          @WebService
          public class EmployeeServiceImpl implements EmployeeService {

              @Override
              public boolean insertEmployee(Employee e) {
                  //業(yè)務(wù)想咋整自已實現(xiàn)去吧,我這里作例子,就直接回true了,呵呵
                  return true;
              }

              @Override
              public boolean updateEmployee(String id) {
                  //業(yè)務(wù)想咋整自已實現(xiàn)去吧,我這里作例子,就直接回true了,呵呵
                  return true;
              }

              @Override
              public boolean deleteEmployee(String id) {
                  //業(yè)務(wù)想咋整自已實現(xiàn)去吧,我這里作例子,就直接回true了,呵呵
                  return true;
              }

              @Override
              public Employee seletctEmployee(String id) {
                  Employee e = new Employee();
                  e.setAddress("http://業(yè)務(wù)想咋整自已實現(xiàn)去吧,我這里作例子,就直接回true了,呵呵");
                  e.setId("http://業(yè)務(wù)想咋整自已實現(xiàn)去吧,我這里作例子,就直接回true了,呵呵");
                  e.setName("http://業(yè)務(wù)想咋整自已實現(xiàn)去吧,我這里作例子,就直接回true了,呵呵");
                  return e;
              }

          }
          package test;
          import org.apache.cxf.endpoint.Server;
          import org.apache.cxf.jaxws.JaxWsServerFactoryBean;
          import com.cxf.service.EmployeeServiceImpl;
          public class MainServer {
              public static void main(String[] args) {         
                  JaxWsServerFactoryBean factory = new JaxWsServerFactoryBean();
                  factory.setServiceClass(EmployeeServiceImpl.class);
                  factory.setAddress("http://192.9.11.53:8088/employeeService");         
                  Server server = factory.create();
                  server.start();
              }
          }
          package test;

          import org.apache.cxf.jaxws.JaxWsProxyFactoryBean;

          import com.cxf.bean.Employee;
          import com.cxf.service.EmployeeService;

          public class EmployeeServiceClient {
              public static void main(String[] args) {
                  JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean();
                  factory.setAddress("http://192.9.11.53:8088/employeeService");
                  factory.setServiceClass(EmployeeService.class);
                  EmployeeService es = (EmployeeService) factory.create();
                  Employee e = new Employee();
                  e= es.seletctEmployee("id");
                  System.out.println("地址:"+e.getAddress()+"         姓名:"+e.getName()+"         編號:"+e.getId());
                  System.out.println(es.seletctEmployee("test"));
              }
          }
          //在eclipse里跑發(fā)布類后瀏覽器中訪問http://192.9.11.53:8088/employeeService?wsdl得到描述wsdl
          <wsdl:definitions name="EmployeeServiceImplService" targetNamespace="http://service.cxf.com/"><wsdl:types><xs:schema elementFormDefault="unqualified" targetNamespace="http://service.cxf.com/" version="1.0"><xs:element name="deleteEmployee" type="tns:deleteEmployee"/><xs:element name="deleteEmployeeResponse" type="tns:deleteEmployeeResponse"/><xs:element name="insertEmployee" type="tns:insertEmployee"/><xs:element name="insertEmployeeResponse" type="tns:insertEmployeeResponse"/><xs:element name="seletctEmployee" type="tns:seletctEmployee"/><xs:element name="seletctEmployeeResponse" type="tns:seletctEmployeeResponse"/><xs:element name="updateEmployee" type="tns:updateEmployee"/><xs:element name="updateEmployeeResponse" type="tns:updateEmployeeResponse"/><xs:complexType name="updateEmployee"><xs:sequence><xs:element minOccurs="0" name="arg0" type="xs:string"/></xs:sequence></xs:complexType><xs:complexType name="updateEmployeeResponse"><xs:sequence><xs:element name="return" type="xs:boolean"/></xs:sequence></xs:complexType><xs:complexType name="insertEmployee"><xs:sequence><xs:element minOccurs="0" name="arg0" type="tns:employee"/></xs:sequence></xs:complexType><xs:complexType name="employee"><xs:sequence><xs:element minOccurs="0" name="address" type="xs:string"/><xs:element minOccurs="0" name="id" type="xs:string"/><xs:element minOccurs="0" name="name" type="xs:string"/></xs:sequence></xs:complexType><xs:complexType name="insertEmployeeResponse"><xs:sequence><xs:element name="return" type="xs:boolean"/></xs:sequence></xs:complexType><xs:complexType name="deleteEmployee"><xs:sequence><xs:element minOccurs="0" name="arg0" type="xs:string"/></xs:sequence></xs:complexType><xs:complexType name="deleteEmployeeResponse"><xs:sequence><xs:element name="return" type="xs:boolean"/></xs:sequence></xs:complexType><xs:complexType name="seletctEmployee"><xs:sequence><xs:element minOccurs="0" name="arg0" type="xs:string"/></xs:sequence></xs:complexType><xs:complexType name="seletctEmployeeResponse"><xs:sequence><xs:element minOccurs="0" name="return" type="tns:employee"/></xs:sequence></xs:complexType></xs:schema></wsdl:types><wsdl:message name="insertEmployeeResponse"><wsdl:part element="tns:insertEmployeeResponse" name="parameters">
              </wsdl:part></wsdl:message><wsdl:message name="updateEmployee"><wsdl:part element="tns:updateEmployee" name="parameters">
              </wsdl:part></wsdl:message><wsdl:message name="insertEmployee"><wsdl:part element="tns:insertEmployee" name="parameters">
              </wsdl:part></wsdl:message><wsdl:message name="updateEmployeeResponse"><wsdl:part element="tns:updateEmployeeResponse" name="parameters">
              </wsdl:part></wsdl:message><wsdl:message name="deleteEmployeeResponse"><wsdl:part element="tns:deleteEmployeeResponse" name="parameters">
              </wsdl:part></wsdl:message><wsdl:message name="seletctEmployee"><wsdl:part element="tns:seletctEmployee" name="parameters">
              </wsdl:part></wsdl:message><wsdl:message name="seletctEmployeeResponse"><wsdl:part element="tns:seletctEmployeeResponse" name="parameters">
              </wsdl:part></wsdl:message><wsdl:message name="deleteEmployee"><wsdl:part element="tns:deleteEmployee" name="parameters">
              </wsdl:part></wsdl:message><wsdl:portType name="EmployeeService"><wsdl:operation name="updateEmployee"><wsdl:input message="tns:updateEmployee" name="updateEmployee">
              </wsdl:input><wsdl:output message="tns:updateEmployeeResponse" name="updateEmployeeResponse">
              </wsdl:output></wsdl:operation><wsdl:operation name="insertEmployee"><wsdl:input message="tns:insertEmployee" name="insertEmployee">
              </wsdl:input><wsdl:output message="tns:insertEmployeeResponse" name="insertEmployeeResponse">
              </wsdl:output></wsdl:operation><wsdl:operation name="deleteEmployee"><wsdl:input message="tns:deleteEmployee" name="deleteEmployee">
              </wsdl:input><wsdl:output message="tns:deleteEmployeeResponse" name="deleteEmployeeResponse">
              </wsdl:output></wsdl:operation><wsdl:operation name="seletctEmployee"><wsdl:input message="tns:seletctEmployee" name="seletctEmployee">
              </wsdl:input><wsdl:output message="tns:seletctEmployeeResponse" name="seletctEmployeeResponse">
              </wsdl:output></wsdl:operation></wsdl:portType><wsdl:binding name="EmployeeServiceImplServiceSoapBinding" type="tns:EmployeeService"><soap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/><wsdl:operation name="insertEmployee"><soap:operation soapAction="" style="document"/><wsdl:input name="insertEmployee"><soap:body use="literal"/></wsdl:input><wsdl:output name="insertEmployeeResponse"><soap:body use="literal"/></wsdl:output></wsdl:operation><wsdl:operation name="updateEmployee"><soap:operation soapAction="" style="document"/><wsdl:input name="updateEmployee"><soap:body use="literal"/></wsdl:input><wsdl:output name="updateEmployeeResponse"><soap:body use="literal"/></wsdl:output></wsdl:operation><wsdl:operation name="deleteEmployee"><soap:operation soapAction="" style="document"/><wsdl:input name="deleteEmployee"><soap:body use="literal"/></wsdl:input><wsdl:output name="deleteEmployeeResponse"><soap:body use="literal"/></wsdl:output></wsdl:operation><wsdl:operation name="seletctEmployee"><soap:operation soapAction="" style="document"/><wsdl:input name="seletctEmployee"><soap:body use="literal"/></wsdl:input><wsdl:output name="seletctEmployeeResponse"><soap:body use="literal"/></wsdl:output></wsdl:operation></wsdl:binding><wsdl:service name="EmployeeServiceImplService"><wsdl:port binding="tns:EmployeeServiceImplServiceSoapBinding" name="EmployeeServiceImplPort"><soap:address location="http://192.9.11.53:8088/employeeService"/></wsdl:port></wsdl:service></wsdl:definitions>

          posted @ 2011-12-28 20:54 AthrunWang 閱讀(773) | 評論 (0)編輯 收藏
          鑒客 ResultSet 獲取返回記錄數(shù)量

          rs.last();
          int rowCount = rs.getRow();
          rs.beforeFirst();

          posted @ 2011-12-28 20:52 AthrunWang 閱讀(284) | 評論 (0)編輯 收藏
          僅列出標題
          共8頁: 上一頁 1 2 3 4 5 6 7 8 下一頁 
          主站蜘蛛池模板: 伊春市| 丹东市| 扎鲁特旗| 剑河县| 吉安县| 陆良县| 东平县| 色达县| 新晃| 瑞安市| 枣强县| 夏津县| 庆云县| 沂南县| 丰县| 桐乡市| 巴林左旗| 集贤县| 大丰市| 通州区| 武邑县| 石狮市| 鄂托克前旗| 博兴县| 苏州市| 家居| 麻城市| 乾安县| 舟曲县| 涡阳县| 内江市| 徐水县| 龙南县| 关岭| 铜山县| 乐安县| 陆河县| 宜宾市| 宁南县| 林周县| 龙陵县|