athrunwang

纪元
数据加载中……

用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 阅读(5261) | 评论 (0)编辑 收藏
使用org.apache.tools.zip实现zip压缩和解压

原创作品,允许转载,转载时请务必以超链接形式标明文章 原始出处 、作者信息和本声明。否则将追究法律责任。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实现了zip压缩和解压功能.
*   解决了由于java.util.zip包不支持汉字的问题。
*   使用java.util.zip包时,当zip文件中有名字为中文的文件时,
*   就会出现异常:"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];
    }
    
    //压缩文件夹内的文件
    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调用,递归完成目录文件读取
    private void handleDir(File dir , ZipOutputStream zipOut)throws IOException{
        FileInputStream fileIn;
        File[] files;

        files = dir.listFiles();
    
        if(files.length == 0){//如果目录为空,则单独创建之.
            //ZipEntry的isDirectory()方法中,目录以"/"结尾.
            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{
                    //如果指定文件的目录不存在,则创建之.
                    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();
        }
    }

    //设置缓冲区大小
    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 阅读(1550) | 评论 (0)编辑 收藏
java实现zip与unzip

jdk提供了Zip相关的类方便的实现压缩和解压缩。使用方法很简单。下边分别是压缩和解压缩的简单事例
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读取文件是随机读取的,这就造成可能先读取一个文件
                
//而这个文件所在的目录还没有出现过,所以要建出目录来。
                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 阅读(192) | 评论 (0)编辑 收藏
关于NIO对文件读写的简单总结

本篇主要介绍的是关于nio在文件读写方面的简单应用,具体底层实现原理,并未深究。

新的输入/输出(NIO)库是在JDK 1.4中引入的。它与原来的I/O库最重要的区别是数据打包和传输的方式的不同,原来的 I/O 的方式处理数据,而 NIO 的方式处理数据。按块处理数据比按(流式的)字节处理数据要快得多。但是面向块的I/O缺少一些面向流的I/O所具有的优雅性和简单性。

示例代码:使用IONIO读取一个文件中的内容

 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个字节的内容。  
 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个字节的内容。  
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非常重要的两个核心概念:通道与缓冲区。

1)通道
     Channel是对原I/O包中的流的模拟,可以通过它读取和写入数据。拿NIO与原来的I/O做个比较,通道就像是流。
   通道与流的不同之处在于通道是双向的。而流只是在一个方向上移动(一个流必须是InputStream或者OutputStream的子类) 而通道可以用于读、写或者同时用于读写。
     因为它们是双向的,所以通道可以比流更好地反映底层操作系统的真实情况。特别是在UNIX模型中,底层操作系统通道是双向的。

2)缓冲区
       NIO库中,所有数据都是用缓冲区处理的。在读取数据时,它是直接读到缓冲区中的。在写入数据时,它是写入到缓冲区中的。任何时候访问NIO中的数据,您都是将它放到缓冲区中。
   缓冲区实质上是一个数组。通常它是一个字节数组,但是也可以使用其他种类的数组。但是一个缓冲区不仅仅是一个数组。缓冲区提供了对数据的结构化访问,而且还可以跟踪系统的读/写进程。
   最常用的缓冲区类型是ByteBuffer 一个ByteBuffer可以在其底层字节数组上进行get/set操作(即字节的获取和设置)
   ByteBuffer不是NIO中唯一的缓冲区类型。事实上,对于每一种基本Java类型都有一种缓冲区类型:
   ByteBuffer
   CharBuffer
   ShortBuffer

   IntBuffer
   LongBuffer
   FloatBuffer
   DoubleBuffer
   每一个Buffer类都是Buffer接口的一个实例。 

文件的读写

nio读取文件涉及三个步骤:
   (1) FileInputStream获取Channel
   (2) 创建Buffer
   (3) 将数据从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 * 将一个文件的所有内容拷贝到另一个文件中。
10 * 
11 * 基本步骤:
12 * 1.得到输入输出通道,创建缓冲区
13 * 2.从源文件中将数据读到这个缓冲区中,然后将缓冲区写入目标文件.此过程需不断循环直到源文件结束
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        // 创建缓冲区
28        ByteBuffer buffer = ByteBuffer.allocate(1024);
29
30        while (true{
31            // clear方法重设缓冲区,使它可以接受读入的数据
32            buffer.clear();
33
34            // 从输入通道中将数据读到缓冲区
35            int r = fcin.read(buffer);
36
37            // read方法返回读取的字节数,可能为零,如果该通道已到达流的末尾,则返回-1
38            if (r == -1{
39                break;
40            }

41            
42            // flip方法让缓冲区可以将新读入的数据写入另一个通道
43            buffer.flip();
44
45            // 从输出通道中将数据写入缓冲区
46            fcout.write(buffer);
47        }

48    }

49}

50

 关于nio更加详细深入研究请参考:http://zhangshixi.javaeye.com/category/101360

posted @ 2012-01-03 17:28 AthrunWang 阅读(382) | 评论 (0)编辑 收藏
Java 下载支持断点续传

[代码] [Java]代码,服务器端实现

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) {
                                // 断点开始
                                // 响应的格式是:
                                // Content-Range: bytes [文件块的开始字节]-[文件的总大小 - 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("文件续传...");
                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();
            // 设置User-Agent
            httpURLConnection.setRequestProperty("User-Agent", "Net");
            // 设置续传开始
            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 阅读(454) | 评论 (0)编辑 收藏
Java实现文件的复制和新Nio包通道的运用--Thinking in java

首先是二进制读取文件成为字节的代码

  

  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));//构建读取流  
  17.         try{  
  18.             byte[] data = new byte[bf.available()];//构建缓冲区  
  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{//重载构造方法  
  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的控制台输入实现回显功能

  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包的通道功能读取并且写入文件,并在文件的末尾追加内容

  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")));//获得字节流并且通过通道写入  
  18.         fc.close();  
  19.           
  20.         Thread.sleep(500);//等待磁盘写入数据完毕  
  21.           
  22.         fc = new RandomAccessFile("d://bird.txt","rw").getChannel();//随机读取,对文件末尾追加内容  
  23.         fc.position(fc.size());//调整文件指针的位置到文件的末尾  
  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;//文件缓冲字节区,大小可以自己定  
  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);//设定缓冲区  
  20.         while(in.read(buffer) != -1){  
  21.             buffer.flip();//准备写入,防止其他读取,锁住文件  
  22.             out.write(buffer);  
  23.             buffer.clear();//准备读取。将缓冲区清理完毕,移动文件内部指针  
  24.         }  
  25.     }  

posted @ 2012-01-02 14:19 AthrunWang 阅读(589) | 评论 (0)编辑 收藏
主题:JAVA NIO 简介

1.   基本 概念

IO 是主存和外部设备 ( 硬盘、终端和网络等 ) 拷贝数据的过程。 IO 是操作系统的底层功能实现,底层通过 I/O 指令进行完成。

所有语言运行时系统提供执行 I/O 较高级别的工具。 (c printf scanf,java 的面向对象封装 )

2.    Java 标准 io 回顾

Java 标准 IO 类库是 io 面向对象的一种抽象。基于本地方法的底层实现,我们无须关注底层实现。 InputStream\OutputStream( 字节流 ) :一次传送一个字节。 Reader\Writer( 字符流 ) :一次一个字符。

3.    nio 简介

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

    为所有的原始类型提供 (Buffer) 缓存支持。

    字符集编码解码解决方案。

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

    支持锁和内存映射文件的文件访问接口。

    提供多路 (non-bloking) 非阻塞式的高伸缩性网络 I/O

本文将围绕这几个特性进行学习和介绍。

4.   Buffer&Chanel

Channel buffer NIO 是两个最基本的数据类型抽象。

Buffer:

       是一块连续的内存块。

       NIO 数据读或写的中转地。

Channel:

       数据的源头或者数据的目的地

       用于向 buffer 提供数据或者读取 buffer 数据 ,buffer 对象的唯一接口。

        异步 I/O 支持


图1:channel和buffer关系
 

 

例子 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.         // 创建缓冲区  
  19.         ByteBuffer buffer = ByteBuffer.allocate(1024);  
  20.         while (true) {  
  21.             // clear方法重设缓冲区,使它可以接受读入的数据  
  22.             buffer.clear();  
  23.             // 从输入通道中将数据读到缓冲区  
  24.             int r = fcin.read(buffer);  
  25.             // read方法返回读取的字节数,可能为零,如果该通道已到达流的末尾,则返回-1  
  26.             if (r == -1) {  
  27.                 break;  
  28.             }  
  29.             // flip方法让缓冲区可以将新读入的数据写入另一个通道  
  30.             buffer.flip();  
  31.             // 从输出通道中将数据写入缓冲区  
  32.             fcout.write(buffer);  
  33.         }  
  34.     }  
  35. }  

 

其中 buffer 内部结构如下 ( 下图拷贝自资料 ):


图2:buffer内部结构 

一个 buffer 主要由 position,limit,capacity 三个变量来控制读写的过程。此三个变量的含义见如下表格:

参数

写模式    

读模式

position

当前写入的单位数据数量。

当前读取的单位数据位置。

limit

代表最多能写多少单位数据和容量是一样的。

代表最多能读多少单位数据,和之前写入的单位数据量一致。

capacity

buffer 容量

buffer 容量

Buffer 常见方法:

flip(): 写模式转换成读模式

rewind() :将 position 重置为 0 ,一般用于重复读。

clear() :清空 buffer ,准备再次被写入 (position 变成 0 limit 变成 capacity)

compact(): 将未读取的数据拷贝到 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 包下面的例子 ) 以下是参考数据:

       场景 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

字符编码解码 : 字节码本身只是一些数字,放到正确的上下文中被正确被解析。向 ByteBuffer 中存放数据时需要考虑字符集的编码方式,读取展示 ByteBuffer 数据时涉及对字符集解码。

Java.nio.charset 提供了编码解码一套解决方案。

以我们最常见的 http 请求为例,在请求的时候必须对请求进行正确的编码。在得到响应时必须对响应进行正确的解码。

以下代码向 baidu 发一次请求,并获取结果进行显示。例子演示到了 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");// 创建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:发送请求,使用GBK编码  
  18.             channel.write(charset.encode("GET " + "/ HTTP/1.1" + "\r\n\r\n"));  
  19.             //step3:读取数据  
  20.             ByteBuffer buffer = ByteBuffer.allocate(1024);// 创建1024字节的缓冲  
  21.             while (channel.read(buffer) != -1) {  
  22.                 buffer.flip();// flip方法在读缓冲区字节操作之前调用。  
  23.                 System.out.println(charset.decode(buffer));  
  24.                 // 使用Charset.decode方法将字节转换为字符串  
  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

关于非阻塞 IO 将从何为阻塞、何为非阻塞、非阻塞原理和异步核心 API 几个方面来理解。

何为阻塞?

一个常见的网络 IO 通讯流程如下 :



 

图3:网络通讯基本过程

从该网络通讯过程来理解一下何为阻塞 :

在以上过程中若连接还没到来,那么 accept 会阻塞 , 程序运行到这里不得不挂起, CPU 转而执行其他线程。

在以上过程中若数据还没准备好, read 会一样也会阻塞。

阻塞式网络 IO 的特点:多线程处理多个连接。每个线程拥有自己的栈空间并且占用一些 CPU 时间。每个线程遇到外部为准备好的时候,都会阻塞掉。阻塞的结果就是会带来大量的进程上下文切换。且大部分进程上下文切换可能是无意义的。比如假设一个线程监听一个端口,一天只会有几次请求进来,但是该 cpu 不得不为该线程不断做上下文切换尝试,大部分的切换以阻塞告终。

 

何为非阻塞?

下面有个隐喻:

一辆从 A 开往 B 的公共汽车上,路上有很多点可能会有人下车。司机不知道哪些点会有哪些人会下车,对于需要下车的人,如何处理更好?

1. 司机过程中定时询问每个乘客是否到达目的地,若有人说到了,那么司机停车,乘客下车。 ( 类似阻塞式 )

2. 每个人告诉售票员自己的目的地,然后睡觉,司机只和售票员交互,到了某个点由售票员通知乘客下车。 ( 类似非阻塞 )

很显然,每个人要到达某个目的地可以认为是一个线程,司机可以认为是 CPU 。在阻塞式里面,每个线程需要不断的轮询,上下文切换,以达到找到目的地的结果。而在非阻塞方式里,每个乘客 ( 线程 ) 都在睡觉 ( 休眠 ) ,只在真正外部环境准备好了才唤醒,这样的唤醒肯定不会阻塞。

  非阻塞的原理

把整个过程切换成小的任务,通过任务间协作完成。

由一个专门的线程来处理所有的 IO 事件,并负责分发。

事件驱动机制:事件到的时候触发,而不是同步的去监视事件。

线程通讯:线程之间通过 wait,notify 等方式通讯。保证每次上下文切换都是有意义的。减少无谓的进程切换。

以下是异步 IO 的结构:



 

图4:非阻塞基本原理

 

Reactor 就是上面隐喻的售票员角色。每个线程的处理流程大概都是读取数据、解码、计算处理、编码、发送响应。

异步 IO 核心 API

Selector

异步 IO 的核心类,它能检测一个或多个通道 (channel) 上的事件,并将事件分发出去。

使用一个 select 线程就能监听多个通道上的事件,并基于事件驱动触发相应的响应。而不需要为每个 channel 去分配一个线程。

SelectionKey

包含了事件的状态信息和时间对应的通道的绑定。

例子 1 单线程实现监听两个端口。 ( nio.asyn 包下面的例子。 )

例子 2 NIO 线程协作实现资源合理利用。 (wait,notify) ( nio.asyn.multithread 下的例子 )

posted @ 2012-01-02 13:33 AthrunWang 阅读(192) | 评论 (0)编辑 收藏
简单的基于xfire框架发布webserivce服务

前段时间在弄各种框架下的webservice,要弄demo,网上搜罗了许多,都讲得很好,但感觉就是说得很多很复杂,我就想弄个服务出来供我用一下, 要像网上那么做觉着太麻烦,后来参考各路神仙大佬们后,把代码极度缩小,写了个小实例供自个跑着玩,顺便代码贴上,供大伙口水
支持包:xfire框架lib下核心包,自己官网上下去,在这里就不贴了,除此之外有java环境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) {
        //业务想咋整自已实现去吧,我这里作例子,就直接回true了,呵呵
        return false;
    }

    @Override
    public boolean deleteEmployee(String id) {
        //业务想咋整自已实现去吧,我这里作例子,就直接回true了,呵呵
        return false;
    }

    @Override
    public Employee getEmployee(String id) {
        //业务想咋整自已实现去吧,我这里作例子,就直接回true了,呵呵
        Employee e = new Employee();
        e.setAddress("//业务想咋整自已实现去吧,我这里作例子,就直接回true了,呵呵");
        e.setId("//业务想咋整自已实现去吧,我这里作例子,就直接回true了,呵呵");
        e.setName("//业务想咋整自已实现去吧,我这里作例子,就直接回true了,呵呵");
        return e;
    }

    
}
//现在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>
//现在工程完成,可以把容器集成到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 阅读(320) | 评论 (0)编辑 收藏
简单的基于CXF框架发布webserivce服务

前段时间在弄各种框架下的webservice,要弄demo,网上搜罗了许多,都讲得很好,但感觉就是说得很多很复杂,我就想弄个服务出来供我用一下, 要像网上那么做觉着太麻烦,后来参考各路神仙大佬们后,把代码极度缩小,写了个小实例供自个跑着玩,顺便代码贴上,供大伙口水
支持包:cxf框架lib下核心包,自己官网上下去,在这里就不贴了,除此之外有java环境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) {
        //业务想咋整自已实现去吧,我这里作例子,就直接回true了,呵呵
        return true;
    }

    @Override
    public boolean updateEmployee(String id) {
        //业务想咋整自已实现去吧,我这里作例子,就直接回true了,呵呵
        return true;
    }

    @Override
    public boolean deleteEmployee(String id) {
        //业务想咋整自已实现去吧,我这里作例子,就直接回true了,呵呵
        return true;
    }

    @Override
    public Employee seletctEmployee(String id) {
        Employee e = new Employee();
        e.setAddress("//业务想咋整自已实现去吧,我这里作例子,就直接回true了,呵呵");
        e.setId("//业务想咋整自已实现去吧,我这里作例子,就直接回true了,呵呵");
        e.setName("//业务想咋整自已实现去吧,我这里作例子,就直接回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里跑发布类后浏览器中访问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 阅读(758) | 评论 (0)编辑 收藏
鉴客 ResultSet 获取返回记录数量

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

posted @ 2011-12-28 20:52 AthrunWang 阅读(272) | 评论 (0)编辑 收藏
仅列出标题
共8页: 上一页 1 2 3 4 5 6 7 8 下一页