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

两种方式
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:[email protected]/test/response.txt。

  在JAVA程序中,使用如下方式获得一个远程共享文件的句柄:SmbFile file = new SmbFile("smb://guest:[email protected]/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的用法
import jcifs.smb.SmbFileInputStream;
import jcifs.smb.SmbFile;
public class ReadShareFile {

 public static void main(String[] args) {
     
  try{
   SmbFile smbFile=new SmbFile("smb://test:[email protected]/share2/aa.txt");
    //通过 smbFile.isDirectory();isFile()可以判断smbFile是文件还是文件夹
   int length=smbFile.getContentLength();//得到文件的大小
   byte buffer[] = new byte[length] ;
   SmbFileInputStream in = new SmbFileInputStream(smbFile) ;  //建立smb文件输入流
   while((in.read(buffer)) != -1){
    
    System.out.write(buffer);
    System.out.println(buffer.length);
   }
   in.close();
  }catch(Exception e){
   e.printStackTrace();
  }

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



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

                    }
                    is.write(buffer);
                    in.close();
                    is.close();



例子1: 基于Apache Common-net Ftp实例 http://www.iteye.com/topic/1118804
package com.shine.Ftp.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPClientConfig;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPListParseEngine;
import org.apache.commons.net.ftp.FTPReply;

public class FTPUtil {

	private FTPClient ftp = null;
	/**
	 * Ftp服务器
	 */
	private String server;
	/**
	 * 用户名
	 */
	private String uname;
	/**
	 * 密码
	 */
	private String password;
	/**
	 * 连接端口,默认21
	 */
	private int port = 21;

	public FTPUtil() {

	}
	/**
	 * 连接FTP服务器
	 * 
	 * @param server
	 * @param uname
	 * @param password
	 * @return
	 * @throws Exception
	 */
	public FTPClient connectFTPServer(String server, int port, String uname,
			String password) throws Exception {
		
		//初始化并保存信息
		this.server = server ;
		this.port = port ;
		this.uname = uname ;
		this.password = password ;
		
		ftp = new FTPClient();
		try {
			ftp.configure(getFTPClientConfig());
			ftp.connect(this.server, this.port);
			ftp.login(this.uname, this.password);

			// 文件类型,默认是ASCII
			ftp.setFileType(FTPClient.BINARY_FILE_TYPE);

			// 设置被动模式
			ftp.enterLocalPassiveMode();

			ftp.setConnectTimeout(2000);
			ftp.setControlEncoding("GBK");

			// 响应信息
			int replyCode = ftp.getReplyCode();
			if ((!FTPReply.isPositiveCompletion(replyCode))) {
				// 关闭Ftp连接
				closeFTPClient();
				// 释放空间
				ftp = null;
				throw new Exception("登录FTP服务器失败,请检查![Server:" + server + "、"
						+ "User:" + uname + "、" + "Password:" + password);
			} else {
				return ftp;
			}
		} catch (Exception e) {
			ftp.disconnect();
			ftp = null;
			throw e;
		}
	}

	/**
	 * 配置FTP连接参数
	 * 
	 * @return
	 * @throws Exception
	 */
	public FTPClientConfig getFTPClientConfig() throws Exception {

		String systemKey = FTPClientConfig.SYST_NT;
		String serverLanguageCode = "zh";
		FTPClientConfig conf = new FTPClientConfig(systemKey);
		conf.setServerLanguageCode(serverLanguageCode);
		conf.setDefaultDateFormatStr("yyyy-MM-dd");

		return conf;
	}

	/**
	 * 上传文件到FTP根目录
	 * 
	 * @param localFile
	 * @param newName
	 * @throws Exception
	 */
	public void uploadFile(String localFile, String newName) throws Exception {
		InputStream input = null;
		try {
			File file = null;
			if (checkFileExist(localFile)) {
				file = new File(localFile);
			}
			input = new FileInputStream(file);
			boolean result = ftp.storeFile(newName, input);
			if (!result) {
				throw new Exception("文件上传失败!");
			}
		} catch (Exception e) {
			throw e;
		} finally {
			if (input != null) {
				input.close();
			}
		}
	}

	/**
	 * 上传文件到FTP根目录
	 * 
	 * @param input
	 * @param newName
	 * @throws Exception
	 */
	public void uploadFile(InputStream input, String newName) throws Exception {
		try {
			boolean result = ftp.storeFile(newName, input);
			if (!result) {
				throw new Exception("文件上传失败!");
			}
		} catch (Exception e) {
			throw e;
		} finally {
			if (input != null) {
				input.close();
			}
		}

	}

	/**
	 * 上传文件到指定的FTP路径下
	 * 
	 * @param localFile
	 * @param newName
	 * @param remoteFoldPath
	 * @throws Exception
	 */
	public void uploadFile(String localFile, String newName,
			String remoteFoldPath) throws Exception {
		InputStream input = null;
		try {
			File file = null;
			if (checkFileExist(localFile)) {
				file = new File(localFile);
			}
			input = new FileInputStream(file);

			// 改变当前路径到指定路径
			this.changeDirectory(remoteFoldPath);
			boolean result = ftp.storeFile(newName, input);
			if (!result) {
				throw new Exception("文件上传失败!");
			}

		} catch (Exception e) {
			throw e;
		} finally {
			if (input != null) {
				input.close();
			}
		}
	}

	/**
	 * 上传文件到指定的FTP路径下
	 * 
	 * @param input
	 * @param newName
	 * @param remoteFoldPath
	 * @throws Exception
	 */
	public void uploadFile(InputStream input, String newName,
			String remoteFoldPath) throws Exception {
		try {
			// 改变当前路径到指定路径
			this.changeDirectory(remoteFoldPath);
			boolean result = ftp.storeFile(newName, input);
			if (!result) {
				throw new Exception("文件上传失败!");
			}
		} catch (Exception e) {
			throw e;
		} finally {
			if (input != null) {
				input.close();
			}
		}
	}

	/**
	 * 从FTP指定的路径下载文件
	 * 
	 * @param remotePath
	 * @param localPath
	 */
	public void downloadFile(String remotePath, String localPath)
			throws Exception {

		OutputStream output = null;
		try {
			File file = null;
			if (checkFileExist(localPath)) {
				file = new File(localPath);
			}
			output = new FileOutputStream(file);
			boolean result = ftp.retrieveFile(remotePath, output);
			if (!result) {
				throw new Exception("文件下载失败!");
			}
		} catch (Exception e) {
			throw e;
		} finally {
			if (output != null) {
				output.close();
			}
		}

	}

	/**
	 * 从FTP指定的路径下载文件
	 * 
	 * @param remoteFilePath
	 * @return
	 * @throws Exception
	 */
	public InputStream downFile(String remoteFilePath) throws Exception {
		return ftp.retrieveFileStream(remoteFilePath);
	}

	/**
	 * 获取FTP服务器上指定路径下的文件列表
	 * 
	 * @param filePath
	 * @return
	 */
	public List<String> getFtpServerFileList(String filePath) throws Exception {
		
		List<String> nlist = new ArrayList<String>();
		FTPListParseEngine engine = ftp.initiateListParsing(filePath);
		List<FTPFile> ftpfiles = Arrays.asList(engine.getNext(25));
		
		return getFTPServerFileList(nlist,ftpfiles);
	}

	/**
	 * 获取FTP服务器上指定路径下的文件列表
	 * @param path
	 * @return
	 * @throws Exception
	 */
	public List<String> getFileList(String path) throws Exception {
		
		List<String> nlist = new ArrayList<String>();
		List<FTPFile> ftpfiles = Arrays.asList(ftp.listFiles(path));
		
		return getFTPServerFileList(nlist,ftpfiles);
	}
	
	/**
	 * 列出FTP服务器文件列表信息
	 * @param nlist
	 * @param ftpFiles
	 * @return
	 */
	public List<String> getFTPServerFileList(List<String> nlist,List<FTPFile> ftpFiles){
		if(ftpFiles==null || ftpFiles.size()==0)
			return nlist;
		for (FTPFile ftpFile : ftpFiles) {
			if (ftpFile.isFile()) {
				nlist.add(ftpFile.getName());
			}
		}
		return nlist;
	}
	

	/**
	 * 改变工作目录,如失败则创建文件夹
	 * 
	 * @param remoteFoldPath
	 */
	public void changeDirectory(String remoteFoldPath) throws Exception {

		if (remoteFoldPath != null) {
			boolean flag = ftp.changeWorkingDirectory(remoteFoldPath);
			if (!flag) {
				ftp.makeDirectory(remoteFoldPath);
				ftp.changeWorkingDirectory(remoteFoldPath);
			}
		}

	}

	/**
	 * 检查文件是否存在
	 * 
	 * @param filePath
	 * @return
	 * @throws Exception
	 */
	public boolean checkFileExist(String filePath) throws Exception {
		boolean flag = false;
		File file = new File(filePath);
		if (!file.exists()) {
			throw new Exception("文件不存在,请检查!");
		} else {
			flag = true;
		}
		return flag;
	}

	/**
	 * 获取文件名,不包括后缀
	 * 
	 * @param filePath
	 * @return
	 */
	public String getFileNamePrefix(String filePath) throws Exception {

		boolean flag = this.checkFileExist(filePath);
		if (flag) {
			File file = new File(filePath);
			String fileName = file.getName();
			String _fileName = fileName.substring(0, fileName.lastIndexOf("."));
			return _fileName;
		}
		return null;
	}

	/**
	 * 关闭FTP连接
	 * 
	 * @param ftp
	 * @throws Exception
	 */
	public void closeFTPClient(FTPClient ftp) throws Exception {

		try {
			if (ftp.isConnected())
				ftp.disconnect();
		} catch (Exception e) {
			throw new Exception("关闭FTP服务出错!");
		}
	}

	/**
	 * 关闭FTP连接
	 * 
	 * @throws Exception
	 */
	public void closeFTPClient() throws Exception {

		this.closeFTPClient(this.ftp);

	}

	/**
	 * Get Attribute Method
	 * 
	 */
	public FTPClient getFtp() {
		return ftp;
	}

	public String getServer() {
		return server;
	}

	public String getUname() {
		return uname;
	}

	public String getPassword() {
		return password;
	}

	public int getPort() {
		return port;
	}
	
	/**
	 *  Set Attribute Method
	 * 
	 */
	public void setFtp(FTPClient ftp) {
		this.ftp = ftp;
	}

	public void setServer(String server) {
		this.server = server;
	}

	public void setUname(String uname) {
		this.uname = uname;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public void setPort(int port) {
		this.port = port;
	}

	/**
	 * 主方法(测试)
	 * 
	 * @param args
	 */
	public static void main(String[] args) {
		try {
			FTPUtil fu = new FTPUtil();
			fu.connectFTPServer("192.168.11.28", 21, "Ftpuser", "sunshine");
					} catch (Exception e) {
			System.out.println("异常信息:" + e.getMessage());
		}
	}
}




例子2: 利用commons-net包实现ftp上传下载例子 http://sosuny.iteye.com/blog/888884
下载文件的时候注意一下,第一个参数要用iso-8859_1编码的,否则文件大小等于0!
直接贴图代码了:
package ftp2;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.SocketException;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPClientConfig;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;

/**
 * 使用commons的net包进行ftp链接. 相关包:commons-net-1.4.1.jar ;
 * commons-io-1.2.jar;jakarta-oro-2.0.8.jar测试通过.可以列出ftp上的文件
 * 通过把ftp服务器上的文件流连接到outSteam及可以把文件下载到本机的目录..限制如果目录为中文则需要处理.最好使用英文文件名
 * 
 */
public class ListFtpFile {

	private FTPClient ftpClient = new FTPClient();

	private OutputStream outSteam = null;

	/**
	 * ftp服务器地址
	 */
	private String hostName = "192.168.0.2";
	private int port = 212;

	/**
	 * 登录名
	 */
	private String userName = "anonymous";//匿名登录

	/**
	 * 登录密码
	 */
	private String password = "[email protected]";//随便一个地址

	/**
	 * 需要访问的远程目录
	 */
	private String remoteDir = "/software/dreamweaver/";

	/**
	 * 下载
	 */
	private void download() {
		try {
			// 链接到ftp服务器
			ftpClient.connect(hostName,port);
			System.out.println("连接到ftp服务器:" + hostName + " 成功..开始登录");
			// 登录.用户名 密码
			boolean b = ftpClient.login(userName, password);
			System.out.println("登录成功." + b);
			
//			检测连接是否成功
			int reply = ftpClient.getReplyCode();
			if(!FTPReply.isPositiveCompletion(reply)) {
				ftpClient.disconnect();
				System.err.println("FTP server refused connection.");
				System.exit(1);
			}
			
			ftpClient.setControlEncoding("GBK");
			FTPClientConfig conf = new FTPClientConfig(FTPClientConfig.SYST_NT);  
			conf.setServerLanguageCode("zh"); 
			FTPFile[] remoteFiles = ftpClient.listFiles(remoteDir);
			if (remoteFiles != null) {
				for (int i = 0; i < remoteFiles.length; i++) {
					String name = remoteFiles[i].getName();
					
					//下载
					File localFile = new File("c:/001/ftp/" + name);
					OutputStream is = new FileOutputStream(localFile);
					//retrieveFile的第一个参数需要是 ISO-8859-1 编码,并且必须是完整路径!
					String fileName = remoteDir + name;
					ftpClient.retrieveFile(new String(fileName.getBytes("GBK"),"ISO-8859-1"), is);
					is.close();
					
					//打印
					long length = remoteFiles[i].getSize();
					String readableLength = FileUtils.byteCountToDisplaySize(length);
					System.out.println(name + ":\t"+remoteFiles[i].isFile()+"\t" + readableLength);
					
				}
			}
			

			ftpClient.logout();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			IOUtils.closeQuietly(outSteam);
			try {
				ftpClient.disconnect();
			} catch (IOException ioe) {
				ioe.printStackTrace();
			}
		}
	}
	
	/**
	 * 上传
	 * */
	public void upload(){
		String srcUrl = "C:/001/菜单权限设计.doc";
		String targetFileName = "菜单权限设计.doc";
		try {
			ftpClient.connect(hostName,port);
			boolean b = ftpClient.login(userName, password);
			// 检测连接是否成功
			int reply = ftpClient.getReplyCode();
			if (!FTPReply.isPositiveCompletion(reply)) {
				ftpClient.disconnect();
				System.err.println("FTP server refused connection.");
				System.exit(1);
			}
			
			ftpClient.setControlEncoding("GBK");
			FTPClientConfig conf = new FTPClientConfig(FTPClientConfig.SYST_NT);  
			conf.setServerLanguageCode("zh"); 
			
			File srcFile = new File(srcUrl);
			FileInputStream fis = null;
			fis = new FileInputStream(srcFile);

			// 设置上传目录
			ftpClient.changeWorkingDirectory(remoteDir);
			ftpClient.setBufferSize(1024);
			ftpClient.setControlEncoding("GBK");

			// 设置文件类型(二进制)
			ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
			// 上传
			b = ftpClient.storeFile(targetFileName, fis);
			IOUtils.closeQuietly(fis);
			
			/*boolean bool = ftpClient.changeWorkingDirectory("/NC");
			System.out.println("changeWorkingDirectory="+bool);
			bool = ftpClient.makeDirectory("/NC");
			System.out.println("makeDirectory="+bool);*/
			
			ftpClient.logout();
		} catch (SocketException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			try {
				ftpClient.disconnect();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
	}

	/**
	 * 测试
	 * */
	public static void main(String[] args) {
		ListFtpFile listFtpfiles = new ListFtpFile();
		listFtpfiles.download();
		listFtpfiles.upload();
	}
}


java apache.commons.net ftp 上传下载移动删除 http://www.yanjoy.com/node/39
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.SocketException;
import java.util.TimeZone;
 
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPClientConfig;
import org.apache.commons.net.ftp.FTPReply;
 
 
 
/**
 * @spring.bean id="apachecommonsnetftp"
 * @author lhb http://www.yanjoy.com
 * 
 */
public  class FTPCommon implements FTPInterface {
 
    private Log log = LogFactory.getLog(this.getClass());
     
    private FTPClient ftpClient;
     
    private String username;
 
    private String password;
 
    private String url;
 
    private int port;
 
    public FTPCommon() {
        super();
        // 从配置文件中读取初始化信息
        this.ftpClient = new FTPClient();
         
    }
 
    /**
     * 连接并登录FTP服务器
     * 
     */
    public boolean ftpLogin() {
        this.ftpClient = new FTPClient();
        boolean isLogin = false;
        FTPClientConfig ftpClientConfig = new FTPClientConfig(
                FTPClientConfig.SYST_NT);
        ftpClientConfig.setServerTimeZoneId(TimeZone.getDefault().getID());
        this.ftpClient.setControlEncoding("UTF-8");
        this.ftpClient.configure(ftpClientConfig);
        try {
            if (this.port> 0) {
                this.ftpClient.connect(this.url, this.port);
            } else {
                this.ftpClient.connect(this.url);
            }
            // FTP服务器连接回答
            int reply = this.ftpClient.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                this.ftpClient.disconnect();
                return isLogin;
            }
            if(!this.ftpClient.login(this.username, this.password)){
                return isLogin;
            }
            //this.ftpClient.changeWorkingDirectory(this.ftpEntity.getRemoteDir());
            this.ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
//            log.infoOutPut("成功登陆FTP服务器:" + this.ftpEntity.getUrl() + " 端口号:"
//                    + this.getFtpModel().getPort() + " 目录:"
//                    + this.ftpEntity.getRemoteDir());
            isLogin = true;
        } catch (SocketException e) {
            e.printStackTrace();
//            log.logPrint("连接FTP服务失败!", Constants.LOG_EXCEPTION);
//            log.logPrint(e.getMessage(), Constants.LOG_EXCEPTION);
        } catch (IOException e) {
            e.printStackTrace();
//            log.logPrint("登录FTP服务失败!", Constants.LOG_EXCEPTION);
//            log.logPrint(e.getMessage(), Constants.LOG_EXCEPTION);
        }
        System.out.println(this.ftpClient.getBufferSize());
        this.ftpClient.setBufferSize(1024 * 2);
        this.ftpClient.setDataTimeout(2000);
        return isLogin;
    }
 
    /**
     * 退出并关闭FTP连接
     * 
     */
    public void close() {
        if (null != this.ftpClient && this.ftpClient.isConnected()) {
            try {
                boolean reuslt = this.ftpClient.logout();// 退出FTP服务器
                if (reuslt) {
//                    log.info("退出并关闭FTP服务器的连接");
                }
            } catch (IOException e) {
                e.printStackTrace();
                log.error("退出FTP服务器异常!");
                log.error(e.getMessage());
            } finally {
                try {
                    this.ftpClient.disconnect();// 关闭FTP服务器的连接
                } catch (IOException e) {
                    e.printStackTrace();
                    log.error("关闭FTP服务器的连接异常!");
                    log.error(e.getMessage());
                }
            }
        }
    }
 
    /**
     * 检查FTP服务器是否关闭,如果关闭接则连接登录FTP
    * 
     * @return
     */
    public boolean isOpenFTPConnection() {
        boolean isOpen = false;
        if (null == this.ftpClient) {
            return false;
        }
        try {
            // 没有连接
            if (!this.ftpClient.isConnected()) {
                isOpen = this.ftpLogin();
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("FTP服务器连接登录异常!");
            log.error(e.getMessage());
            isOpen = false;
        }
        return isOpen;
    }
 
    /**
     * 设置传输文件的类型[文本文件或者二进制文件]
     * 
     * @param fileType--FTPClient.BINARY_FILE_TYPE,FTPClient.ASCII_FILE_TYPE
     */
    public void setFileType(int fileType) {
        try {
            this.ftpClient.setFileType(fileType);
        } catch (IOException e) {
            e.printStackTrace();
//            log.exception("设置传输文件的类型异常!");
//            log.exception(e.getMessage());
        }
    }
 
    /**
     * 下载文件
     * 
     * @param localFilePath
     *            本地文件名及路径
     * @param remoteFileName
     *            远程文件名称
     * @return
     */
    public boolean downloadFile(String localFilePath, String remoteFileName) {
        BufferedOutputStream outStream = null;
        boolean success = false;
        try {
            outStream = new BufferedOutputStream(new FileOutputStream(
                    localFilePath));
            success = this.ftpClient.retrieveFile(remoteFileName, outStream);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (outStream != null) {
                try {
                    outStream.flush();
                    outStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return success;
    }
 
    /**
     * 下载文件
     * 
     * @param localFilePath
     *            本地文件
     * @param remoteFileName
     *            远程文件名称
     * @return
     */
    public boolean downloadFile(File localFile, String remoteFileName) {
        BufferedOutputStream outStream = null;
        FileOutputStream outStr = null;
        InputStream inStream = null;
        boolean success = false;
        try {
            outStr = new FileOutputStream(localFile);
            outStream = new BufferedOutputStream(outStr);
            //success = this.ftpClient.retrieveFile(remoteFileName, outStream);
            inStream = this.ftpClient.retrieveFileStream(remoteFileName);
            byte[] bytes = new byte[1024]; 
            int c; 
            while ((c = inStream.read(bytes)) != -1) 
            { 
                outStr.write(bytes, 0, c); 
            } 
             
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != outStream) {
                    try {
                        outStream.flush();
                        outStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if(null != inStream){
                    inStream.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                 
                    try {
                        if (null != outStr) {
                            outStr.flush();
                            outStr.close();
                        }
                        if(null != inStream){
                            inStream.close();
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
 
                 
                 
            }
        }
        return success;
    }
     
    /**
     * 
     * @param outStream
     * @param remoteFileName
     * @return
     */
    public OutputStream downloadFile(OutputStream outStream, String remoteFileName) {
        BufferedOutputStream bufferOutStream = null;
        boolean success = false;
        try {
            bufferOutStream = new BufferedOutputStream(outStream);
            success = this.ftpClient.retrieveFile(remoteFileName, bufferOutStream);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } 
        return bufferOutStream;
    }
 
    /**
     * 上传文件
     * 
     * @param localFilePath
     *            本地文件路径及名称
     * @param remoteFileName
     *            FTP 服务器文件名称
     * @return
     */
    public boolean uploadFile(String localFilePath, String remoteFileName) {
        BufferedInputStream inStream = null;
        OutputStream osStrem = null;
        boolean success = false;
        try {
            inStream = new BufferedInputStream(new FileInputStream(
                    localFilePath));
            osStrem = this.ftpClient.storeFileStream(remoteFileName);
            byte[] bytes = new byte[1024];
            int c;
            while ((c = inStream.read(bytes)) != -1) {
                osStrem.write(bytes, 0, c);
            }
            success = true;
            //success = this.ftpClient.storeFile(new String(remoteFileName.getBytes("UTF-8"), "ISO-8859-1"), inStream);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
             
                try {
                    if (inStream != null) {
                        inStream.close();
                    }
                    if(osStrem!=null){
                        osStrem.flush();
                        osStrem.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
             
        }
        return success;
    }
 
    /**
     * 上传文件
     * 
     * @param localFilePath
     *            本地文件
     * @param remoteFileName
     *            FTP 服务器文件名称
     * @return
     */
    public boolean uploadFile(File localFile, String remoteFileName) {
        BufferedInputStream inStream = null;
        boolean success = false;
        try {
            inStream = new BufferedInputStream(new FileInputStream(localFile));
            success = this.ftpClient.storeFile(remoteFileName, inStream);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (inStream != null) {
                try {
                    inStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return success;
    }
     
 
     
    /**
     * 删除FTP服务器上文件
     * @param remoteFileName
     *          FTP 服务器文件名称
     * @return
     */
    public boolean delFile(String remoteFileName){
        boolean success = false;
        try {            
            success = this.ftpClient.deleteFile(remoteFileName);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } 
        return success;
    }
     
    /**
     * 删除FTP服务器上文件夹中的所有文件
     * @param remoteDir
     * @return
     */
    public boolean delAllFile(String remoteDir){
        boolean success = false;
        try {
            this.ftpClient.changeWorkingDirectory(remoteDir);
            String files[] = null;
            files = this.ftpClient.listNames();
            if(files!=null){
                for(int i=0;i<files.length;i++){
                    success = this.ftpClient.deleteFile(files[i]);
                }
            }           
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } 
        return success;
    }
     
    /**
     * 删除FTP服务器上文件夹中的所有文件
     * @param remoteDir
     * @return
     */
    public boolean delAllFile(){
        boolean success = false;
        try {            
            String files[] = null;
            files = this.ftpClient.listNames();
            if(files!=null){
                for(int i=0;i<files.length;i++){
                    success = this.ftpClient.deleteFile(files[i]);
                }
            }           
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } 
        return success;
    }
     
    /**
     * 删除目录
     * @param pathname
     * @return
     */
    public boolean deleteDirectory(String pathname){
        boolean success = false;
        try {            
            success = this.ftpClient.removeDirectory(pathname);         
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } 
        return success;
    }
     
    /**
     * 移动文件或重命名
     * @param fromFile
     * @param toFile
     * @return
     */
    public boolean moveFile(String fromFile, String toFile) {
        boolean success = false;
        try {            
            success = this.ftpClient.rename(fromFile, toFile);         
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } 
        return success;
    }
     
    /**
     * 创建文件夹
     * @param dir
     * @return
     */
    public boolean makeDirectory(String dir){
        boolean success = false;
        try {            
            success = this.ftpClient.makeDirectory(dir);         
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } 
        return success;
    }
     
 
    /**
     * 变更工作目录
     * 
     * @param remoteDir--目录路径
     */
    public void changeDir(String remoteDir) {
        try {
            this.ftpClient.changeWorkingDirectory(remoteDir);
//            log.info("变更工作目录为:" + remoteDir);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("变更工作目录为:" + remoteDir + "时出错!");
            log.error(e.getMessage());
        }
 
    }
 
    /**
     * 变更工作目录
     * 
     * @param remoteDir--目录路径
     */
    public void changeDir(String[] remoteDirs) {
        String dir = "";
        try {
            for (int i = 0; i < remoteDirs.length; i++) {
                this.ftpClient.changeWorkingDirectory(remoteDirs[i]);
                dir = dir + remoteDirs[i] + "/";
            }
//            log.info("变更工作目录为:" + dir);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("变更工作目录为:" + dir + "时出错!");
            log.error(e.getMessage());
        }
 
    }
 
    /**
     * 返回上级目录
     * 
     */
    public void toParentDir(String[] remoteDirs) {
        try {
            for (int i = 0; i < remoteDirs.length; i++) {
                this.ftpClient.changeToParentDirectory();
            }
//            log.info("返回上级目录");
        } catch (IOException e) {
            e.printStackTrace();
            log.error("返回上级目录时出错!");
            log.error(e.getMessage());
        }
    }
 
    /**
     * 返回上级目录
     * 
     */
    public void toParentDir() {
        try {
            this.ftpClient.changeToParentDirectory();
            log.info("返回上级目录");
        } catch (IOException e) {
            e.printStackTrace();
            log.error("返回上级目录时出错!");
            log.error(e.getMessage());
        }
    }
 
    /**
     * 获得FTP 服务器下所有的文件名列表
     * 
     * @param regex
     * @return
     */
    public String[] getListFiels() {
        String files[] = null;
        try {
            files = this.ftpClient.listNames();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return files;
    }
 
    public FTPClient getFtpClient() {
        return ftpClient;
    }
 
 
 
    public void init(String server,
                     int port,
                     String userName,
                     String userPassword) {
        // TODO Auto-generated method stub
        this.url = server;
        this.port =port;
        this.username = userName;        
        this.password = userPassword;
         
    }
 
 
}






java.net支持: Java读取远程文件[Http,ftp],并保存
import java.net.*;
import java.io.*;
/*
* Created on 2007-6-1
*
* TODO To change the template for this generated file go to
* Window - Preferences - Java - Code Style - Code Templates
*/

/**
* @author howard
*
* TODO To change the template for this generated type comment go to
* Window - Preferences - Java - Code Style - Code Templates
*/
public class TestUrl {

public boolean saveUrlAs(String photoUrl, String fileName) {
     try {
      URL url = new URL(photoUrl);
      HttpURLConnection connection = (HttpURLConnection) url
        .openConnection();
      DataInputStream in = new DataInputStream(connection
        .getInputStream());
      DataOutputStream out = new DataOutputStream(new FileOutputStream(
        fileName));
      byte[] buffer = new byte[4096];
      int count = 0;
      while ((count = in.read(buffer)) > 0) {
       out.write(buffer, 0, count);
      }
      out.close();
      in.close();
      return true;

     } catch (Exception e) {
      System.out.println(e);
      return false;
     }
    }
    /**
     * 兼容HTTP和FTP协议
     * @param urlString
     * @return
     */
    public String getDocumentAt(String urlString) {
     StringBuffer document = new StringBuffer();

     try {

      URL url = new URL(urlString);
      URLConnection conn = url.openConnection();
      BufferedReader reader = new BufferedReader(new InputStreamReader(
        conn.getInputStream()));
      String line = null;
      while ((line = reader.readLine()) != null) {
       document.append(line + "\n");
      }
      reader.close();
     } catch (MalformedURLException e) {
      System.out.println("Unable to connect to URL: " + urlString);
     } catch (IOException e) {
      System.out.println("IOException when connecting to URL: "
        + urlString);
     }
     return document.toString();
    }

    /**
     * 
     * @param args
     */
    public static void main(String[] args) {
     TestUrl test = new TestUrl();
     String photoUrl = "http://www.zhplc.com/468x60.gif";
     String fileName = photoUrl.substring(photoUrl.lastIndexOf("/"));
     String filePath = "c:\\";
     boolean flag = test.saveUrlAs(photoUrl, filePath + fileName);
     System.out.println("Run ok!\n Get URL file " + flag);
    }

   }

猜你喜欢

转载自panyongzheng.iteye.com/blog/2215968