java跨服务器保存文件:jcifs & FTP

来源:互联网 发布:淘宝人像摄影 编辑:程序博客网 时间:2024/06/10 01:40

 原文章地址:http://panyongzheng.iteye.com/blog/2215968


两种方式 
1.使用共享网络磁盘的形式,在当前的服务器简历一个另一台服务器的网络磁盘,直接操作读写这个网络磁盘即可
2.使用FTP操作另外这台服务器 

帖子1:java上传图片到另一台服务器上,如何解决? 
http://bbs.csdn.net/topics/370033090?page=1#post-394318586 

使用org.apache.commons.net.ftp包开发FTP客户端,实现进度汇报,实现断点续传,中文支持 
利用org.apache.commons.net.ftp包实现一个简单的ftp客户端实用类。主要实现一下功能 
1.支持上传下载。支持断点续传 
2.支持进度汇报 
3.支持对于中文目录及中文文件创建的支持。 
http://zhangnet1.iteye.com/blog/907109 


两个工具: 
1. 有人介绍用jcifs-1.1.11.jar,这个可以在远程服务器上创建文件夹 
2. apache的ftp工具 
3. java.net支持 

通过jcifs实现java访问网络共享文件 
在Microsoft 网 络 系 统 中,SMB(Server Message Block,服务信息块)协议是WindowsforWorkgroup(WfWg)、Windows95、WindowsNT和LanManager用来实现共享局域网上文件和打印机的协议。对于利用Linux和WindowsNT构建的局域网来说,Samba就是为Linux提供的SMB客户程序/服务器程序的软件包,其功能是实现Windows 和Linux互相共享对方的磁盘空间和打印机。通用网络文件系统简称CIFS,它事实上是windows平台文件共享的标准协议,它是windows explorer,网络邻居和映射网络驱动器的底层实现协议。JAVA具有天然的平台无关性,使用JAVA可以访问任何类型的服务器或客户机上的共享文件系统,并且编写的软件产品可以运行于任何平台,因此用JAVA访问共享文件系统在企业应用中具有得天独厚的优势。 
jcifs是CIFS在JAVA中的一个实现,是samba组织负责维护开发的一个开源项目,专注于使用java语言对cifs协议的设计和实现。他们将jcifs设计成为一个完整的,丰富的,具有可扩展能力且线程安全的客户端库。这一库可以应用于各种java虚拟机访问遵循CIFS/SMB网络传输协议的网络资源。类似于java.io.File的接口形式,在多线程的工作方式下被证明是有效而容易使用的。 

  jcifs的开发方法类似java的文件操作功能,它的资源url定位:smb://{user}:{password}@{host}/{path},smb为协议名,user和password分别为共享文件机子的登陆名和密码,@后面是要访问的资源的主机名或IP地址。最后是资源的共享文件夹名称和共享资源名。例如 smb://administrator:122122@192.168.0.22/test/response.txt。 

  在JAVA程序中,使用如下方式获得一个远程共享文件的句柄:SmbFile file = new SmbFile("smb://guest:1234@192.168.3.56/share/a.txt");这里的句柄不仅限于远程的共享文件,还可能是共享文件夹。isFile()方法和isDirectory()用来判断这个句柄对应的资源的真实属性。如果是共享文件夹,通过调用它的list()方法将获得其中资源的列表。List方法支持过滤器机制,有两种过滤器可供使用,一种是SmbFileFilter,另一种是SmbFilenameFilter,这两个在jcifs中作为接口出现,你可以根据自己的需要派生出个性化的过滤器,实现接口中的accept方法,以满足不同业务的需求。 

  SmbFileInputStream是smb文件的输入流,它的功能是以流的方式打开一个SmbFile:SmbFileInputStream in = new SmbFileInputStream(file);SmbFileInputStream提供read方法,你可以从这个流中读出远程文件全部的内容。 

SmbFileInputStream,SmbFileOutputStream,SmbFile这里对应着io里的FileInputStream 
FileOutputStream,File,如果对io比较熟悉那么jcifs比较容易应用 
下面一个最简单的例子说明jcifs的用法 

Java代码  收藏代码
  1. import jcifs.smb.SmbFileInputStream;  
  2. import jcifs.smb.SmbFile;  
  3. public class ReadShareFile {  
  4.   
  5.  public static void main(String[] args) {  
  6.        
  7.   try{  
  8.    SmbFile smbFile=new SmbFile("smb://test:test@10.218.100.12/share2/aa.txt");  
  9.     //通过 smbFile.isDirectory();isFile()可以判断smbFile是文件还是文件夹  
  10.    int length=smbFile.getContentLength();//得到文件的大小  
  11.    byte buffer[] = new byte[length] ;  
  12.    SmbFileInputStream in = new SmbFileInputStream(smbFile) ;  //建立smb文件输入流  
  13.    while((in.read(buffer)) != -1){  
  14.       
  15.     System.out.write(buffer);  
  16.     System.out.println(buffer.length);  
  17.    }  
  18.    in.close();  
  19.   }catch(Exception e){  
  20.    e.printStackTrace();  
  21.   }  

smb://guest:1234@192.168.3.56/share/a.txt 
这个url的开始部分smb:// 说明了这是一个smb类型的url;接下来的guest和1234分别是访问共享资源的用户名称和密码;@后面是要访问的资源的主机名或IP地址。最后是资源的共享文件夹名称和共享资源名。 



Commons Net, 这个包还是很实用的,封装了很多网络协议。 
要设定二进制方式,否在一些文件不完整。 
Java代码  收藏代码
  1. //设置被动模式     
  2. ftpClient.enterLocalPassiveMode();     
  3. //设置以二进制方式传输     
  4. ftpClient.setFileType(FTP.BINARY_FILE_TYPE);   
  
如果使用InputStream读取字节流,不能一次读写完, 要分次读取 
Java代码  收藏代码
  1. InputStream in  =ftpClient.retrieveFileStream(new String(downLoadFileName.getBytes("UTF-8"), "UTF-8"));  
  2.                     //int size=in.available();  
  3.                     Long t = ftpFile.getSize();  
  4.                     int size=t.intValue();  
  5.                     byte[] buffer = new byte[t.intValue()];  
  6.                     byte[] tmp = new byte[1024];  
  7.                     int length = -1;  
  8.                     int count=0;  
  9.                     while ((length=in.read(tmp))!= -1) {  
  10.                         System.arraycopy(tmp, 0, buffer, count, length);  
  11.                         count=count+length;  
  12.   
  13.                     }  
  14.                     is.write(buffer);  
  15.                     in.close();  
  16.                     is.close();  



例子1: 基于Apache Common-net Ftp实例 http://www.iteye.com/topic/1118804 
Java代码  收藏代码
  1. package com.shine.Ftp.util;  
  2.   
  3. import java.io.File;  
  4. import java.io.FileInputStream;  
  5. import java.io.FileOutputStream;  
  6. import java.io.InputStream;  
  7. import java.io.OutputStream;  
  8. import java.util.ArrayList;  
  9. import java.util.Arrays;  
  10. import java.util.List;  
  11.   
  12. import org.apache.commons.net.ftp.FTPClient;  
  13. import org.apache.commons.net.ftp.FTPClientConfig;  
  14. import org.apache.commons.net.ftp.FTPFile;  
  15. import org.apache.commons.net.ftp.FTPListParseEngine;  
  16. import org.apache.commons.net.ftp.FTPReply;  
  17.   
  18. public class FTPUtil {  
  19.   
  20.     private FTPClient ftp = null;  
  21.     /** 
  22.      * Ftp服务器 
  23.      */  
  24.     private String server;  
  25.     /** 
  26.      * 用户名 
  27.      */  
  28.     private String uname;  
  29.     /** 
  30.      * 密码 
  31.      */  
  32.     private String password;  
  33.     /** 
  34.      * 连接端口,默认21 
  35.      */  
  36.     private int port = 21;  
  37.   
  38.     public FTPUtil() {  
  39.   
  40.     }  
  41.     /** 
  42.      * 连接FTP服务器 
  43.      *  
  44.      * @param server 
  45.      * @param uname 
  46.      * @param password 
  47.      * @return 
  48.      * @throws Exception 
  49.      */  
  50.     public FTPClient connectFTPServer(String server, int port, String uname,  
  51.             String password) throws Exception {  
  52.           
  53.         //初始化并保存信息  
  54.         this.server = server ;  
  55.         this.port = port ;  
  56.         this.uname = uname ;  
  57.         this.password = password ;  
  58.           
  59.         ftp = new FTPClient();  
  60.         try {  
  61.             ftp.configure(getFTPClientConfig());  
  62.             ftp.connect(this.server, this.port);  
  63.             ftp.login(this.uname, this.password);  
  64.   
  65.             // 文件类型,默认是ASCII  
  66.             ftp.setFileType(FTPClient.BINARY_FILE_TYPE);  
  67.   
  68.             // 设置被动模式  
  69.             ftp.enterLocalPassiveMode();  
  70.   
  71.             ftp.setConnectTimeout(2000);  
  72.             ftp.setControlEncoding("GBK");  
  73.   
  74.             // 响应信息  
  75.             int replyCode = ftp.getReplyCode();  
  76.             if ((!FTPReply.isPositiveCompletion(replyCode))) {  
  77.                 // 关闭Ftp连接  
  78.                 closeFTPClient();  
  79.                 // 释放空间  
  80.                 ftp = null;  
  81.                 throw new Exception("登录FTP服务器失败,请检查![Server:" + server + "、"  
  82.                         + "User:" + uname + "、" + "Password:" + password);  
  83.             } else {  
  84.                 return ftp;  
  85.             }  
  86.         } catch (Exception e) {  
  87.             ftp.disconnect();  
  88.             ftp = null;  
  89.             throw e;  
  90.         }  
  91.     }  
  92.   
  93.     /** 
  94.      * 配置FTP连接参数 
  95.      *  
  96.      * @return 
  97.      * @throws Exception 
  98.      */  
  99.     public FTPClientConfig getFTPClientConfig() throws Exception {  
  100.   
  101.         String systemKey = FTPClientConfig.SYST_NT;  
  102.         String serverLanguageCode = "zh";  
  103.         FTPClientConfig conf = new FTPClientConfig(systemKey);  
  104.         conf.setServerLanguageCode(serverLanguageCode);  
  105.         conf.setDefaultDateFormatStr("yyyy-MM-dd");  
  106.   
  107.         return conf;  
  108.     }  
  109.   
  110.     /** 
  111.      * 上传文件到FTP根目录 
  112.      *  
  113.      * @param localFile 
  114.      * @param newName 
  115.      * @throws Exception 
  116.      */  
  117.     public void uploadFile(String localFile, String newName) throws Exception {  
  118.         InputStream input = null;  
  119.         try {  
  120.             File file = null;  
  121.             if (checkFileExist(localFile)) {  
  122.                 file = new File(localFile);  
  123.             }  
  124.             input = new FileInputStream(file);  
  125.             boolean result = ftp.storeFile(newName, input);  
  126.             if (!result) {  
  127.                 throw new Exception("文件上传失败!");  
  128.             }  
  129.         } catch (Exception e) {  
  130.             throw e;  
  131.         } finally {  
  132.             if (input != null) {  
  133.                 input.close();  
  134.             }  
  135.         }  
  136.     }  
  137.   
  138.     /** 
  139.      * 上传文件到FTP根目录 
  140.      *  
  141.      * @param input 
  142.      * @param newName 
  143.      * @throws Exception 
  144.      */  
  145.     public void uploadFile(InputStream input, String newName) throws Exception {  
  146.         try {  
  147.             boolean result = ftp.storeFile(newName, input);  
  148.             if (!result) {  
  149.                 throw new Exception("文件上传失败!");  
  150.             }  
  151.         } catch (Exception e) {  
  152.             throw e;  
  153.         } finally {  
  154.             if (input != null) {  
  155.                 input.close();  
  156.             }  
  157.         }  
  158.   
  159.     }  
  160.   
  161.     /** 
  162.      * 上传文件到指定的FTP路径下 
  163.      *  
  164.      * @param localFile 
  165.      * @param newName 
  166.      * @param remoteFoldPath 
  167.      * @throws Exception 
  168.      */  
  169.     public void uploadFile(String localFile, String newName,  
  170.             String remoteFoldPath) throws Exception {  
  171.         InputStream input = null;  
  172.         try {  
  173.             File file = null;  
  174.             if (checkFileExist(localFile)) {  
  175.                 file = new File(localFile);  
  176.             }  
  177.             input = new FileInputStream(file);  
  178.   
  179.             // 改变当前路径到指定路径  
  180.             this.changeDirectory(remoteFoldPath);  
  181.             boolean result = ftp.storeFile(newName, input);  
  182.             if (!result) {  
  183.                 throw new Exception("文件上传失败!");  
  184.             }  
  185.   
  186.         } catch (Exception e) {  
  187.             throw e;  
  188.         } finally {  
  189.             if (input != null) {  
  190.                 input.close();  
  191.             }  
  192.         }  
  193.     }  
  194.   
  195.     /** 
  196.      * 上传文件到指定的FTP路径下 
  197.      *  
  198.      * @param input 
  199.      * @param newName 
  200.      * @param remoteFoldPath 
  201.      * @throws Exception 
  202.      */  
  203.     public void uploadFile(InputStream input, String newName,  
  204.             String remoteFoldPath) throws Exception {  
  205.         try {  
  206.             // 改变当前路径到指定路径  
  207.             this.changeDirectory(remoteFoldPath);  
  208.             boolean result = ftp.storeFile(newName, input);  
  209.             if (!result) {  
  210.                 throw new Exception("文件上传失败!");  
  211.             }  
  212.         } catch (Exception e) {  
  213.             throw e;  
  214.         } finally {  
  215.             if (input != null) {  
  216.                 input.close();  
  217.             }  
  218.         }  
  219.     }  
  220.   
  221.     /** 
  222.      * 从FTP指定的路径下载文件 
  223.      *  
  224.      * @param remotePath 
  225.      * @param localPath 
  226.      */  
  227.     public void downloadFile(String remotePath, String localPath)  
  228.             throws Exception {  
  229.   
  230.         OutputStream output = null;  
  231.         try {  
  232.             File file = null;  
  233.             if (checkFileExist(localPath)) {  
  234.                 file = new File(localPath);  
  235.             }  
  236.             output = new FileOutputStream(file);  
  237.             boolean result = ftp.retrieveFile(remotePath, output);  
  238.             if (!result) {  
  239.                 throw new Exception("文件下载失败!");  
  240.             }  
  241.         } catch (Exception e) {  
  242.             throw e;  
  243.         } finally {  
  244.             if (output != null) {  
  245.                 output.close();  
  246.             }  
  247.         }  
  248.   
  249.     }  
  250.   
  251.     /** 
  252.      * 从FTP指定的路径下载文件 
  253.      *  
  254.      * @param remoteFilePath 
  255.      * @return 
  256.      * @throws Exception 
  257.      */  
  258.     public InputStream downFile(String remoteFilePath) throws Exception {  
  259.         return ftp.retrieveFileStream(remoteFilePath);  
  260.     }  
  261.   
  262.     /** 
  263.      * 获取FTP服务器上指定路径下的文件列表 
  264.      *  
  265.      * @param filePath 
  266.      * @return 
  267.      */  
  268.     public List<String> getFtpServerFileList(String filePath) throws Exception {  
  269.           
  270.         List<String> nlist = new ArrayList<String>();  
  271.         FTPListParseEngine engine = ftp.initiateListParsing(filePath);  
  272.         List<FTPFile> ftpfiles = Arrays.asList(engine.getNext(25));  
  273.           
  274.         return getFTPServerFileList(nlist,ftpfiles);  
  275.     }  
  276.   
  277.     /** 
  278.      * 获取FTP服务器上指定路径下的文件列表 
  279.      * @param path 
  280.      * @return 
  281.      * @throws Exception 
  282.      */  
  283.     public List<String> getFileList(String path) throws Exception {  
  284.           
  285.         List<String> nlist = new ArrayList<String>();  
  286.         List<FTPFile> ftpfiles = Arrays.asList(ftp.listFiles(path));  
  287.           
  288.         return getFTPServerFileList(nlist,ftpfiles);  
  289.     }  
  290.       
  291.     /** 
  292.      * 列出FTP服务器文件列表信息 
  293.      * @param nlist 
  294.      * @param ftpFiles 
  295.      * @return 
  296.      */  
  297.     public List<String> getFTPServerFileList(List<String> nlist,List<FTPFile> ftpFiles){  
  298.         if(ftpFiles==null || ftpFiles.size()==0)  
  299.             return nlist;  
  300.         for (FTPFile ftpFile : ftpFiles) {  
  301.             if (ftpFile.isFile()) {  
  302.                 nlist.add(ftpFile.getName());  
  303.             }  
  304.         }  
  305.         return nlist;  
  306.     }  
  307.       
  308.   
  309.     /** 
  310.      * 改变工作目录,如失败则创建文件夹 
  311.      *  
  312.      * @param remoteFoldPath 
  313.      */  
  314.     public void changeDirectory(String remoteFoldPath) throws Exception {  
  315.   
  316.         if (remoteFoldPath != null) {  
  317.             boolean flag = ftp.changeWorkingDirectory(remoteFoldPath);  
  318.             if (!flag) {  
  319.                 ftp.makeDirectory(remoteFoldPath);  
  320.                 ftp.changeWorkingDirectory(remoteFoldPath);  
  321.             }  
  322.         }  
  323.   
  324.     }  
  325.   
  326.     /** 
  327.      * 检查文件是否存在 
  328.      *  
  329.      * @param filePath 
  330.      * @return 
  331.      * @throws Exception 
  332.      */  
  333.     public boolean checkFileExist(String filePath) throws Exception {  
  334.         boolean flag = false;  
  335.         File file = new File(filePath);  
  336.         if (!file.exists()) {  
  337.             throw new Exception("文件不存在,请检查!");  
  338.         } else {  
  339.             flag = true;  
  340.         }  
  341.         return flag;  
  342.     }  
  343.   
  344.     /** 
  345.      * 获取文件名,不包括后缀 
  346.      *  
  347.      * @param filePath 
  348.      * @return 
  349.      */  
  350.     public String getFileNamePrefix(String filePath) throws Exception {  
  351.   
  352.         boolean flag = this.checkFileExist(filePath);  
  353.         if (flag) {  
  354.             File file = new File(filePath);  
  355.             String fileName = file.getName();  
  356.             String _fileName = fileName.substring(0, fileName.lastIndexOf("."));  
  357.             return _fileName;  
  358.         }  
  359.         return null;  
  360.     }  
  361.   
  362.     /** 
  363.      * 关闭FTP连接 
  364.      *  
  365.      * @param ftp 
  366.      * @throws Exception 
  367.      */  
  368.     public void closeFTPClient(FTPClient ftp) throws Exception {  
  369.   
  370.         try {  
  371.             if (ftp.isConnected())  
  372.                 ftp.disconnect();  
  373.         } catch (Exception e) {  
  374.             throw new Exception("关闭FTP服务出错!");  
  375.         }  
  376.     }  
  377.   
  378.     /** 
  379.      * 关闭FTP连接 
  380.      *  
  381.      * @throws Exception 
  382.      */  
  383.     public void closeFTPClient() throws Exception {  
  384.   
  385.         this.closeFTPClient(this.ftp);  
  386.   
  387.     }  
  388.   
  389.     /** 
  390.      * Get Attribute Method 
  391.      *  
  392.      */  
  393.     public FTPClient getFtp() {  
  394.         return ftp;  
  395.     }  
  396.   
  397.     public String getServer() {  
  398.         return server;  
  399.     }  
  400.   
  401.     public String getUname() {  
  402.         return uname;  
  403.     }  
  404.   
  405.     public String getPassword() {  
  406.         return password;  
  407.     }  
  408.   
  409.     public int getPort() {  
  410.         return port;  
  411.     }  
  412.       
  413.     /** 
  414.      *  Set Attribute Method 
  415.      *  
  416.      */  
  417.     public void setFtp(FTPClient ftp) {  
  418.         this.ftp = ftp;  
  419.     }  
  420.   
  421.     public void setServer(String server) {  
  422.         this.server = server;  
  423.     }  
  424.   
  425.     public void setUname(String uname) {  
  426.         this.uname = uname;  
  427.     }  
  428.   
  429.     public void setPassword(String password) {  
  430.         this.password = password;  
  431.     }  
  432.   
  433.     public void setPort(int port) {  
  434.         this.port = port;  
  435.     }  
  436.   
  437.     /** 
  438.      * 主方法(测试) 
  439.      *  
  440.      * @param args 
  441.      */  
  442.     public static void main(String[] args) {  
  443.         try {  
  444.             FTPUtil fu = new FTPUtil();  
  445.             fu.connectFTPServer("192.168.11.28"21"Ftpuser""sunshine");  
  446.                     } catch (Exception e) {  
  447.             System.out.println("异常信息:" + e.getMessage());  
  448.         }  
  449.     }  
  450. }  




例子2: 利用commons-net包实现ftp上传下载例子 http://sosuny.iteye.com/blog/888884 
下载文件的时候注意一下,第一个参数要用iso-8859_1编码的,否则文件大小等于0! 
直接贴图代码了: 
Java代码  收藏代码
  1. package ftp2;  
  2.   
  3. import java.io.File;  
  4. import java.io.FileInputStream;  
  5. import java.io.FileOutputStream;  
  6. import java.io.IOException;  
  7. import java.io.OutputStream;  
  8. import java.net.SocketException;  
  9.   
  10. import org.apache.commons.io.FileUtils;  
  11. import org.apache.commons.io.IOUtils;  
  12. import org.apache.commons.net.ftp.FTPClient;  
  13. import org.apache.commons.net.ftp.FTPClientConfig;  
  14. import org.apache.commons.net.ftp.FTPFile;  
  15. import org.apache.commons.net.ftp.FTPReply;  
  16.   
  17. /** 
  18.  * 使用commons的net包进行ftp链接. 相关包:commons-net-1.4.1.jar ; 
  19.  * commons-io-1.2.jar;jakarta-oro-2.0.8.jar测试通过.可以列出ftp上的文件 
  20.  * 通过把ftp服务器上的文件流连接到outSteam及可以把文件下载到本机的目录..限制如果目录为中文则需要处理.最好使用英文文件名 
  21.  *  
  22.  */  
  23. public class ListFtpFile {  
  24.   
  25.     private FTPClient ftpClient = new FTPClient();  
  26.   
  27.     private OutputStream outSteam = null;  
  28.   
  29.     /** 
  30.      * ftp服务器地址 
  31.      */  
  32.     private String hostName = "192.168.0.2";  
  33.     private int port = 212;  
  34.   
  35.     /** 
  36.      * 登录名 
  37.      */  
  38.     private String userName = "anonymous";//匿名登录  
  39.   
  40.     /** 
  41.      * 登录密码 
  42.      */  
  43.     private String password = "121@hotmail.com";//随便一个地址  
  44.   
  45.     /** 
  46.      * 需要访问的远程目录 
  47.      */  
  48.     private String remoteDir = "/software/dreamweaver/";  
  49.   
  50.     /** 
  51.      * 下载 
  52.      */  
  53.     private void download() {  
  54.         try {  
  55.             // 链接到ftp服务器  
  56.             ftpClient.connect(hostName,port);  
  57.             System.out.println("连接到ftp服务器:" + hostName + " 成功..开始登录");  
  58.             // 登录.用户名 密码  
  59.             boolean b = ftpClient.login(userName, password);  
  60.             System.out.println("登录成功." + b);  
  61.               
  62. //          检测连接是否成功  
  63.             int reply = ftpClient.getReplyCode();  
  64.             if(!FTPReply.isPositiveCompletion(reply)) {  
  65.                 ftpClient.disconnect();  
  66.                 System.err.println("FTP server refused connection.");  
  67.                 System.exit(1);  
  68.             }  
  69.               
  70.             ftpClient.setControlEncoding("GBK");  
  71.             FTPClientConfig conf = new FTPClientConfig(FTPClientConfig.SYST_NT);    
  72.             conf.setServerLanguageCode("zh");   
  73.             FTPFile[] remoteFiles = ftpClient.listFiles(remoteDir);  
  74.             if (remoteFiles != null) {  
  75.                 for (int i = 0; i < remoteFiles.length; i++) {  
  76.                     String name = remoteFiles[i].getName();  
  77.                       
  78.                     //下载  
  79.                     File localFile = new File("c:/001/ftp/" + name);  
  80.                     OutputStream is = new FileOutputStream(localFile);  
  81.                     //retrieveFile的第一个参数需要是 ISO-8859-1 编码,并且必须是完整路径!  
  82.                     String fileName = remoteDir + name;  
  83.                     ftpClient.retrieveFile(new String(fileName.getBytes("GBK"),"ISO-8859-1"), is);  
  84.                     is.close();  
  85.                       
  86.                     //打印  
  87.                     long length = remoteFiles[i].getSize();  
  88.                     String readableLength = FileUtils.byteCountToDisplaySize(length);  
  89.                     System.out.println(name + ":\t"+remoteFiles[i].isFile()+"\t" + readableLength);  
  90.                       
  91.                 }  
  92.             }  
  93.               
  94.   
  95.             ftpClient.logout();  
  96.         } catch (Exception e) {  
  97.             e.printStackTrace();  
  98.         } finally {  
  99.             IOUtils.closeQuietly(outSteam);  
  100.             try {  
  101.                 ftpClient.disconnect();  
  102.             } catch (IOException ioe) {  
  103.                 ioe.printStackTrace();  
  104.             }  
  105.         }  
  106.     }  
  107.       
  108.     /** 
  109.      * 上传 
  110.      * */  
  111.     public void upload(){  
  112.         String srcUrl = "C:/001/菜单权限设计.doc";  
  113.         String targetFileName = "菜单权限设计.doc";  
  114.         try {  
  115.             ftpClient.connect(hostName,port);  
  116.             boolean b = ftpClient.login(userName, password);  
  117.             // 检测连接是否成功  
  118.             int reply = ftpClient.getReplyCode();  
  119.             if (!FTPReply.isPositiveCompletion(reply)) {  
  120.                 ftpClient.disconnect();  
  121.                 System.err.println("FTP server refused connection.");  
  122.                 System.exit(1);  
  123.             }  
  124.               
  125.             ftpClient.setControlEncoding("GBK");  
  126.             FTPClientConfig conf = new FTPClientConfig(FTPClientConfig.SYST_NT);    
  127.             conf.setServerLanguageCode("zh");   
  128.               
  129.             File srcFile = new File(srcUrl);  
  130.             FileInputStream fis = null;  
  131.             fis = new FileInputStream(srcFile);  
  132.   
  133.             // 设置上传目录  
  134.             ftpClient.changeWorkingDirectory(remoteDir);  
  135.             ftpClient.setBufferSize(1024);  
  136.             ftpClient.setControlEncoding("GBK");  
  137.   
  138.             // 设置文件类型(二进制)  
  139.             ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);  
  140.             // 上传  
  141.             b = ftpClient.storeFile(targetFileName, fis);  
  142.             IOUtils.closeQuietly(fis);  
  143.               
  144.             /*boolean bool = ftpClient.changeWorkingDirectory("/NC"); 
  145.             System.out.println("changeWorkingDirectory="+bool); 
  146.             bool = ftpClient.makeDirectory("/NC"); 
  147.             System.out.println("makeDirectory="+bool);*/  
  148.               
  149.             ftpClient.logout();  
  150.         } catch (SocketException e) {  
  151.             e.printStackTrace();  
  152.         } catch (IOException e) {  
  153.             e.printStackTrace();  
  154.         }finally{  
  155.             try {  
  156.                 ftpClient.disconnect();  
  157.             } catch (IOException e) {  
  158.                 e.printStackTrace();  
  159.             }  
  160.         }  
  161.           
  162.     }  
  163.   
  164.     /** 
  165.      * 测试 
  166.      * */  
  167.     public static void main(String[] args) {  
  168.         ListFtpFile listFtpfiles = new ListFtpFile();  
  169.         listFtpfiles.download();  
  170.         listFtpfiles.upload();  
  171.     }  
  172. }  


java apache.commons.net ftp 上传下载移动删除 http://www.yanjoy.com/node/39 
Java代码  收藏代码
  1. import java.io.BufferedInputStream;  
  2. import java.io.BufferedOutputStream;  
  3. import java.io.File;  
  4. import java.io.FileInputStream;  
  5. import java.io.FileNotFoundException;  
  6. import java.io.FileOutputStream;  
  7. import java.io.IOException;  
  8. import java.io.InputStream;  
  9. import java.io.OutputStream;  
  10. import java.net.SocketException;  
  11. import java.util.TimeZone;  
  12.    
  13. import org.apache.commons.logging.Log;  
  14. import org.apache.commons.logging.LogFactory;  
  15. import org.apache.commons.net.ftp.FTPClient;  
  16. import org.apache.commons.net.ftp.FTPClientConfig;  
  17. import org.apache.commons.net.ftp.FTPReply;  
  18.    
  19.    
  20.    
  21. /** 
  22.  * @spring.bean id="apachecommonsnetftp" 
  23.  * @author lhb http://www.yanjoy.com 
  24.  *  
  25.  */  
  26. public  class FTPCommon implements FTPInterface {  
  27.    
  28.     private Log log = LogFactory.getLog(this.getClass());  
  29.        
  30.     private FTPClient ftpClient;  
  31.        
  32.     private String username;  
  33.    
  34.     private String password;  
  35.    
  36.     private String url;  
  37.    
  38.     private int port;  
  39.    
  40.     public FTPCommon() {  
  41.         super();  
  42.         // 从配置文件中读取初始化信息  
  43.         this.ftpClient = new FTPClient();  
  44.            
  45.     }  
  46.    
  47.     /** 
  48.      * 连接并登录FTP服务器 
  49.      *  
  50.      */  
  51.     public boolean ftpLogin() {  
  52.         this.ftpClient = new FTPClient();  
  53.         boolean isLogin = false;  
  54.         FTPClientConfig ftpClientConfig = new FTPClientConfig(  
  55.                 FTPClientConfig.SYST_NT);  
  56.         ftpClientConfig.setServerTimeZoneId(TimeZone.getDefault().getID());  
  57.         this.ftpClient.setControlEncoding("UTF-8");  
  58.         this.ftpClient.configure(ftpClientConfig);  
  59.         try {  
  60.             if (this.port> 0) {  
  61.                 this.ftpClient.connect(this.url, this.port);  
  62.             } else {  
  63.                 this.ftpClient.connect(this.url);  
  64.             }  
  65.             // FTP服务器连接回答  
  66.             int reply = this.ftpClient.getReplyCode();  
  67.             if (!FTPReply.isPositiveCompletion(reply)) {  
  68.                 this.ftpClient.disconnect();  
  69.                 return isLogin;  
  70.             }  
  71.             if(!this.ftpClient.login(this.username, this.password)){  
  72.                 return isLogin;  
  73.             }  
  74.             //this.ftpClient.changeWorkingDirectory(this.ftpEntity.getRemoteDir());  
  75.             this.ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);  
  76. //            log.infoOutPut("成功登陆FTP服务器:" + this.ftpEntity.getUrl() + " 端口号:"  
  77. //                    + this.getFtpModel().getPort() + " 目录:"  
  78. //                    + this.ftpEntity.getRemoteDir());  
  79.             isLogin = true;  
  80.         } catch (SocketException e) {  
  81.             e.printStackTrace();  
  82. //            log.logPrint("连接FTP服务失败!", Constants.LOG_EXCEPTION);  
  83. //            log.logPrint(e.getMessage(), Constants.LOG_EXCEPTION);  
  84.         } catch (IOException e) {  
  85.             e.printStackTrace();  
  86. //            log.logPrint("登录FTP服务失败!", Constants.LOG_EXCEPTION);  
  87. //            log.logPrint(e.getMessage(), Constants.LOG_EXCEPTION);  
  88.         }  
  89.         System.out.println(this.ftpClient.getBufferSize());  
  90.         this.ftpClient.setBufferSize(1024 * 2);  
  91.         this.ftpClient.setDataTimeout(2000);  
  92.         return isLogin;  
  93.     }  
  94.    
  95.     /** 
  96.      * 退出并关闭FTP连接 
  97.      *  
  98.      */  
  99.     public void close() {  
  100.         if (null != this.ftpClient && this.ftpClient.isConnected()) {  
  101.             try {  
  102.                 boolean reuslt = this.ftpClient.logout();// 退出FTP服务器  
  103.                 if (reuslt) {  
  104. //                    log.info("退出并关闭FTP服务器的连接");  
  105.                 }  
  106.             } catch (IOException e) {  
  107.                 e.printStackTrace();  
  108.                 log.error("退出FTP服务器异常!");  
  109.                 log.error(e.getMessage());  
  110.             } finally {  
  111.                 try {  
  112.                     this.ftpClient.disconnect();// 关闭FTP服务器的连接  
  113.                 } catch (IOException e) {  
  114.                     e.printStackTrace();  
  115.                     log.error("关闭FTP服务器的连接异常!");  
  116.                     log.error(e.getMessage());  
  117.                 }  
  118.             }  
  119.         }  
  120.     }  
  121.    
  122.     /** 
  123.      * 检查FTP服务器是否关闭,如果关闭接则连接登录FTP 
  124.     *  
  125.      * @return 
  126.      */  
  127.     public boolean isOpenFTPConnection() {  
  128.         boolean isOpen = false;  
  129.         if (null == this.ftpClient) {  
  130.             return false;  
  131.         }  
  132.         try {  
  133.             // 没有连接  
  134.             if (!this.ftpClient.isConnected()) {  
  135.                 isOpen = this.ftpLogin();  
  136.             }  
  137.         } catch (Exception e) {  
  138.             e.printStackTrace();  
  139.             log.error("FTP服务器连接登录异常!");  
  140.             log.error(e.getMessage());  
  141.             isOpen = false;  
  142.         }  
  143.         return isOpen;  
  144.     }  
  145.    
  146.     /** 
  147.      * 设置传输文件的类型[文本文件或者二进制文件] 
  148.      *  
  149.      * @param fileType--FTPClient.BINARY_FILE_TYPE,FTPClient.ASCII_FILE_TYPE 
  150.      */  
  151.     public void setFileType(int fileType) {  
  152.         try {  
  153.             this.ftpClient.setFileType(fileType);  
  154.         } catch (IOException e) {  
  155.             e.printStackTrace();  
  156. //            log.exception("设置传输文件的类型异常!");  
  157. //            log.exception(e.getMessage());  
  158.         }  
  159.     }  
  160.    
  161.     /** 
  162.      * 下载文件 
  163.      *  
  164.      * @param localFilePath 
  165.      *            本地文件名及路径 
  166.      * @param remoteFileName 
  167.      *            远程文件名称 
  168.      * @return 
  169.      */  
  170.     public boolean downloadFile(String localFilePath, String remoteFileName) {  
  171.         BufferedOutputStream outStream = null;  
  172.         boolean success = false;  
  173.         try {  
  174.             outStream = new BufferedOutputStream(new FileOutputStream(  
  175.                     localFilePath));  
  176.             success = this.ftpClient.retrieveFile(remoteFileName, outStream);  
  177.         } catch (FileNotFoundException e) {  
  178.             e.printStackTrace();  
  179.         } catch (IOException e) {  
  180.             e.printStackTrace();  
  181.         } finally {  
  182.             if (outStream != null) {  
  183.                 try {  
  184.                     outStream.flush();  
  185.                     outStream.close();  
  186.                 } catch (IOException e) {  
  187.                     e.printStackTrace();  
  188.                 }  
  189.             }  
  190.         }  
  191.         return success;  
  192.     }  
  193.    
  194.     /** 
  195.      * 下载文件 
  196.      *  
  197.      * @param localFilePath 
  198.      *            本地文件 
  199.      * @param remoteFileName 
  200.      *            远程文件名称 
  201.      * @return 
  202.      */  
  203.     public boolean downloadFile(File localFile, String remoteFileName) {  
  204.         BufferedOutputStream outStream = null;  
  205.         FileOutputStream outStr = null;  
  206.         InputStream inStream = null;  
  207.         boolean success = false;  
  208.         try {  
  209.             outStr = new FileOutputStream(localFile);  
  210.             outStream = new BufferedOutputStream(outStr);  
  211.             //success = this.ftpClient.retrieveFile(remoteFileName, outStream);  
  212.             inStream = this.ftpClient.retrieveFileStream(remoteFileName);  
  213.             byte[] bytes = new byte[1024];   
  214.             int c;   
  215.             while ((c = inStream.read(bytes)) != -1)   
  216.             {   
  217.                 outStr.write(bytes, 0, c);   
  218.             }   
  219.                
  220.         } catch (FileNotFoundException e) {  
  221.             e.printStackTrace();  
  222.         } catch (IOException e) {  
  223.             e.printStackTrace();  
  224.         } finally {  
  225.             try {  
  226.                 if (null != outStream) {  
  227.                     try {  
  228.                         outStream.flush();  
  229.                         outStream.close();  
  230.                     } catch (IOException e) {  
  231.                         e.printStackTrace();  
  232.                     }  
  233.                 }  
  234.                 if(null != inStream){  
  235.                     inStream.close();  
  236.                 }  
  237.             } catch (Exception e) {  
  238.                 e.printStackTrace();  
  239.             } finally {  
  240.                    
  241.                     try {  
  242.                         if (null != outStr) {  
  243.                             outStr.flush();  
  244.                             outStr.close();  
  245.                         }  
  246.                         if(null != inStream){  
  247.                             inStream.close();  
  248.                         }  
  249.                     } catch (IOException e) {  
  250.                         e.printStackTrace();  
  251.                     }  
  252.    
  253.                    
  254.                    
  255.             }  
  256.         }  
  257.         return success;  
  258.     }  
  259.        
  260.     /** 
  261.      *  
  262.      * @param outStream 
  263.      * @param remoteFileName 
  264.      * @return 
  265.      */  
  266.     public OutputStream downloadFile(OutputStream outStream, String remoteFileName) {  
  267.         BufferedOutputStream bufferOutStream = null;  
  268.         boolean success = false;  
  269.         try {  
  270.             bufferOutStream = new BufferedOutputStream(outStream);  
  271.             success = this.ftpClient.retrieveFile(remoteFileName, bufferOutStream);  
  272.         } catch (FileNotFoundException e) {  
  273.             e.printStackTrace();  
  274.         } catch (IOException e) {  
  275.             e.printStackTrace();  
  276.         }   
  277.         return bufferOutStream;  
  278.     }  
  279.    
  280.     /** 
  281.      * 上传文件 
  282.      *  
  283.      * @param localFilePath 
  284.      *            本地文件路径及名称 
  285.      * @param remoteFileName 
  286.      *            FTP 服务器文件名称 
  287.      * @return 
  288.      */  
  289.     public boolean uploadFile(String localFilePath, String remoteFileName) {  
  290.         BufferedInputStream inStream = null;  
  291.         OutputStream osStrem = null;  
  292.         boolean success = false;  
  293.         try {  
  294.             inStream = new BufferedInputStream(new FileInputStream(  
  295.                     localFilePath));  
  296.             osStrem = this.ftpClient.storeFileStream(remoteFileName);  
  297.             byte[] bytes = new byte[1024];  
  298.             int c;  
  299.             while ((c = inStream.read(bytes)) != -1) {  
  300.                 osStrem.write(bytes, 0, c);  
  301.             }  
  302.             success = true;  
  303.             //success = this.ftpClient.storeFile(new String(remoteFileName.getBytes("UTF-8"), "ISO-8859-1"), inStream);  
  304.         } catch (FileNotFoundException e) {  
  305.             e.printStackTrace();  
  306.         } catch (IOException e) {  
  307.             e.printStackTrace();  
  308.         } finally {  
  309.                
  310.                 try {  
  311.                     if (inStream != null) {  
  312.                         inStream.close();  
  313.                     }  
  314.                     if(osStrem!=null){  
  315.                         osStrem.flush();  
  316.                         osStrem.close();  
  317.                     }  
  318.                 } catch (IOException e) {  
  319.                     e.printStackTrace();  
  320.                 }  
  321.                
  322.         }  
  323.         return success;  
  324.     }  
  325.    
  326.     /** 
  327.      * 上传文件 
  328.      *  
  329.      * @param localFilePath 
  330.      *            本地文件 
  331.      * @param remoteFileName 
  332.      *            FTP 服务器文件名称 
  333.      * @return 
  334.      */  
  335.     public boolean uploadFile(File localFile, String remoteFileName) {  
  336.         BufferedInputStream inStream = null;  
  337.         boolean success = false;  
  338.         try {  
  339.             inStream = new BufferedInputStream(new FileInputStream(localFile));  
  340.             success = this.ftpClient.storeFile(remoteFileName, inStream);  
  341.         } catch (FileNotFoundException e) {  
  342.             e.printStackTrace();  
  343.         } catch (IOException e) {  
  344.             e.printStackTrace();  
  345.         } finally {  
  346.             if (inStream != null) {  
  347.                 try {  
  348.                     inStream.close();  
  349.                 } catch (IOException e) {  
  350.                     e.printStackTrace();  
  351.                 }  
  352.             }  
  353.         }  
  354.         return success;  
  355.     }  
  356.        
  357.    
  358.        
  359.     /** 
  360.      * 删除FTP服务器上文件 
  361.      * @param remoteFileName 
  362.      *          FTP 服务器文件名称 
  363.      * @return 
  364.      */  
  365.     public boolean delFile(String remoteFileName){  
  366.         boolean success = false;  
  367.         try {              
  368.             success = this.ftpClient.deleteFile(remoteFileName);  
  369.         } catch (FileNotFoundException e) {  
  370.             e.printStackTrace();  
  371.         } catch (IOException e) {  
  372.             e.printStackTrace();  
  373.         }   
  374.         return success;  
  375.     }  
  376.        
  377.     /** 
  378.      * 删除FTP服务器上文件夹中的所有文件 
  379.      * @param remoteDir 
  380.      * @return 
  381.      */  
  382.     public boolean delAllFile(String remoteDir){  
  383.         boolean success = false;  
  384.         try {  
  385.             this.ftpClient.changeWorkingDirectory(remoteDir);  
  386.             String files[] = null;  
  387.             files = this.ftpClient.listNames();  
  388.             if(files!=null){  
  389.                 for(int i=0;i<files.length;i++){  
  390.                     success = this.ftpClient.deleteFile(files[i]);  
  391.                 }  
  392.             }             
  393.         } catch (FileNotFoundException e) {  
  394.             e.printStackTrace();  
  395.         } catch (IOException e) {  
  396.             e.printStackTrace();  
  397.         }   
  398.         return success;  
  399.     }  
  400.        
  401.     /** 
  402.      * 删除FTP服务器上文件夹中的所有文件 
  403.      * @param remoteDir 
  404.      * @return 
  405.      */  
  406.     public boolean delAllFile(){  
  407.         boolean success = false;  
  408.         try {              
  409.             String files[] = null;  
  410.             files = this.ftpClient.listNames();  
  411.             if(files!=null){  
  412.                 for(int i=0;i<files.length;i++){  
  413.                     success = this.ftpClient.deleteFile(files[i]);  
  414.                 }  
  415.             }             
  416.         } catch (FileNotFoundException e) {  
  417.             e.printStackTrace();  
  418.         } catch (IOException e) {  
  419.             e.printStackTrace();  
  420.         }   
  421.         return success;  
  422.     }  
  423.        
  424.     /** 
  425.      * 删除目录 
  426.      * @param pathname 
  427.      * @return 
  428.      */  
  429.     public boolean deleteDirectory(String pathname){  
  430.         boolean success = false;  
  431.         try {              
  432.             success = this.ftpClient.removeDirectory(pathname);           
  433.         } catch (FileNotFoundException e) {  
  434.             e.printStackTrace();  
  435.         } catch (IOException e) {  
  436.             e.printStackTrace();  
  437.         }   
  438.         return success;  
  439.     }  
  440.        
  441.     /** 
  442.      * 移动文件或重命名 
  443.      * @param fromFile 
  444.      * @param toFile 
  445.      * @return 
  446.      */  
  447.     public boolean moveFile(String fromFile, String toFile) {  
  448.         boolean success = false;  
  449.         try {              
  450.             success = this.ftpClient.rename(fromFile, toFile);           
  451.         } catch (FileNotFoundException e) {  
  452.             e.printStackTrace();  
  453.         } catch (IOException e) {  
  454.             e.printStackTrace();  
  455.         }   
  456.         return success;  
  457.     }  
  458.        
  459.     /** 
  460.      * 创建文件夹 
  461.      * @param dir 
  462.      * @return 
  463.      */  
  464.     public boolean makeDirectory(String dir){  
  465.         boolean success = false;  
  466.         try {              
  467.             success = this.ftpClient.makeDirectory(dir);           
  468.         } catch (FileNotFoundException e) {  
  469.             e.printStackTrace();  
  470.         } catch (IOException e) {  
  471.             e.printStackTrace();  
  472.         }   
  473.         return success;  
  474.     }  
  475.        
  476.    
  477.     /** 
  478.      * 变更工作目录 
  479.      *  
  480.      * @param remoteDir--目录路径 
  481.      */  
  482.     public void changeDir(String remoteDir) {  
  483.         try {  
  484.             this.ftpClient.changeWorkingDirectory(remoteDir);  
  485. //            log.info("变更工作目录为:" + remoteDir);  
  486.         } catch (IOException e) {  
  487.             e.printStackTrace();  
  488.             log.error("变更工作目录为:" + remoteDir + "时出错!");  
  489.             log.error(e.getMessage());  
  490.         }  
  491.    
  492.     }  
  493.    
  494.     /** 
  495.      * 变更工作目录 
  496.      *  
  497.      * @param remoteDir--目录路径 
  498.      */  
  499.     public void changeDir(String[] remoteDirs) {  
  500.         String dir = "";  
  501.         try {  
  502.             for (int i = 0; i < remoteDirs.length; i++) {  
  503.                 this.ftpClient.changeWorkingDirectory(remoteDirs[i]);  
  504.                 dir = dir + remoteDirs[i] + "/";  
  505.             }  
  506. //            log.info("变更工作目录为:" + dir);  
  507.         } catch (IOException e) {  
  508.             e.printStackTrace();  
  509.             log.error("变更工作目录为:" + dir + "时出错!");  
  510.             log.error(e.getMessage());  
  511.         }  
  512.    
  513.     }  
  514.    
  515.     /** 
  516.      * 返回上级目录 
  517.      *  
  518.      */  
  519.     public void toParentDir(String[] remoteDirs) {  
  520.         try {  
  521.             for (int i = 0; i < remoteDirs.length; i++) {  
  522.                 this.ftpClient.changeToParentDirectory();  
  523.             }  
  524. //            log.info("返回上级目录");  
  525.         } catch (IOException e) {  
  526.             e.printStackTrace();  
  527.             log.error("返回上级目录时出错!");  
  528.             log.error(e.getMessage());  
  529.         }  
  530.     }  
  531.    
  532.     /** 
  533.      * 返回上级目录 
  534.      *  
  535.      */  
  536.     public void toParentDir() {  
  537.         try {  
  538.             this.ftpClient.changeToParentDirectory();  
  539.             log.info("返回上级目录");  
  540.         } catch (IOException e) {  
  541.             e.printStackTrace();  
  542.             log.error("返回上级目录时出错!");  
  543.             log.error(e.getMessage());  
  544.         }  
  545.     }  
  546.    
  547.     /** 
  548.      * 获得FTP 服务器下所有的文件名列表 
  549.      *  
  550.      * @param regex 
  551.      * @return 
  552.      */  
  553.     public String[] getListFiels() {  
  554.         String files[] = null;  
  555.         try {  
  556.             files = this.ftpClient.listNames();  
  557.         } catch (IOException e) {  
  558.             e.printStackTrace();  
  559.         }  
  560.         return files;  
  561.     }  
  562.    
  563.     public FTPClient getFtpClient() {  
  564.         return ftpClient;  
  565.     }  
  566.    
  567.    
  568.    
  569.     public void init(String server,  
  570.                      int port,  
  571.                      String userName,  
  572.                      String userPassword) {  
  573.         // TODO Auto-generated method stub  
  574.         this.url = server;  
  575.         this.port =port;  
  576.         this.username = userName;          
  577.         this.password = userPassword;  
  578.            
  579.     }  
  580.    
  581.    
  582. }  






java.net支持: Java读取远程文件[Http,ftp],并保存 
Java代码  收藏代码
  1. import java.net.*;  
  2. import java.io.*;  
  3. /* 
  4. * Created on 2007-6-1 
  5. * 
  6. * TODO To change the template for this generated file go to 
  7. * Window - Preferences - Java - Code Style - Code Templates 
  8. */  
  9.   
  10. /** 
  11. * @author howard 
  12. * 
  13. * TODO To change the template for this generated type comment go to 
  14. * Window - Preferences - Java - Code Style - Code Templates 
  15. */  
  16. public class TestUrl {  
  17.   
  18. public boolean saveUrlAs(String photoUrl, String fileName) {  
  19.      try {  
  20.       URL url = new URL(photoUrl);  
  21.       HttpURLConnection connection = (HttpURLConnection) url  
  22.         .openConnection();  
  23.       DataInputStream in = new DataInputStream(connection  
  24.         .getInputStream());  
  25.       DataOutputStream out = new DataOutputStream(new FileOutputStream(  
  26.         fileName));  
  27.       byte[] buffer = new byte[4096];  
  28.       int count = 0;  
  29.       while ((count = in.read(buffer)) > 0) {  
  30.        out.write(buffer, 0, count);  
  31.       }  
  32.       out.close();  
  33.       in.close();  
  34.       return true;  
  35.   
  36.      } catch (Exception e) {  
  37.       System.out.println(e);  
  38.       return false;  
  39.      }  
  40.     }  
  41.     /** 
  42.      * 兼容HTTP和FTP协议 
  43.      * @param urlString 
  44.      * @return 
  45.      */  
  46.     public String getDocumentAt(String urlString) {  
  47.      StringBuffer document = new StringBuffer();  
  48.   
  49.      try {  
  50.   
  51.       URL url = new URL(urlString);  
  52.       URLConnection conn = url.openConnection();  
  53.       BufferedReader reader = new BufferedReader(new InputStreamReader(  
  54.         conn.getInputStream()));  
  55.       String line = null;  
  56.       while ((line = reader.readLine()) != null) {  
  57.        document.append(line + "\n");  
  58.       }  
  59.       reader.close();  
  60.      } catch (MalformedURLException e) {  
  61.       System.out.println("Unable to connect to URL: " + urlString);  
  62.      } catch (IOException e) {  
  63.       System.out.println("IOException when connecting to URL: "  
  64.         + urlString);  
  65.      }  
  66.      return document.toString();  
  67.     }  
  68.   
  69.     /** 
  70.      *  
  71.      * @param args 
  72.      */  
  73.     public static void main(String[] args) {  
  74.      TestUrl test = new TestUrl();  
  75.      String photoUrl = "http://www.zhplc.com/468x60.gif";  
  76.      String fileName = photoUrl.substring(photoUrl.lastIndexOf("/"));  
  77.      String filePath = "c:\\";  
  78.      boolean flag = test.saveUrlAs(photoUrl, filePath + fileName);  
  79.      System.out.println("Run ok!\n Get URL file " + flag);  
  80.     }  
  81.   
  82.    }  

0 0
原创粉丝点击