Java中通过FTP上传和下载

一个JAVA实现FTP功能的代码,包括了服务器的设置模块,并包括有上传文件至FTP的通用方法、下载文件的通用方法以及删除文件、在ftp服务器上穿件文件夹、检测文件夹是否存在等,里面的有些代码对编写JAVA文件上传或许有参考价值,直接把代码贴出来了,注释写的很详细,大家可以参考参考.

1.FtpUtil

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;

import sun.net.TelnetOutputStream;
import sun.net.ftp.FtpClient;
import org.apache.log4j.Logger;

public class FtpUtil {
	// 日志
	private static final Logger log = Logger.getLogger(FtpUtil.class);
	private FtpBean ftpBean = null;
	private FtpClient client = null;

	public FtpUtil(FtpBean ftpBean) {
		super();
		this.ftpBean = ftpBean;
	}

	/**
	 * 连接ftp服务
	 * 
	 * @return
	 * @throws IOException
	 */
	public FtpClient openFtp() throws IOException {
		log.debug("正在连接" + ftpBean.getHostName() + ",请等待.....");
		if(ftpBean==null||ftpBean.getHostName()==null||"".equals(ftpBean.getHostName()))
			throw new IOException("Ftp连接地址为空!!!");
		
		client = new FtpClient(ftpBean.getHostName(), ftpBean.getDefaultport());
		client.login(ftpBean.getUserName(), ftpBean.getPassword());
		client.binary();
		log.debug("连接主机:" + ftpBean.getHostName() + "成功!");
		return client;
	}

	/**
	 * 
	 * <p>上传文件或目录: </p>
	 * 
	 * @param sourceSrc
	 *            上传的文件或目录
	 * @param targetSrc
	 *            上传目标目录
	 * @author humf
	 * @return void
	 * @version 1.0
	 */
	public void uploadFile(String sourceSrc, String targetSrc,String rootSrc) throws Exception {
		log.debug("sourceSrc:" + sourceSrc + "<==>targetSrc:" + targetSrc+"<-->"+rootSrc);
		client.cd(rootSrc);
		String root = "";
		File file = new File(sourceSrc);
		if (!file.exists())
			throw new FileNotFoundException();
		
		if (file.isDirectory()) {
			createDir(targetSrc, false);
			File[] files = file.listFiles();
			for (File fs : files) {
				if (!fs.isDirectory()) {
					uplocalFile(fs);
				}
				//log.debug("目录下所有文件名称【" + fs.getAbsolutePath() + "】");
			}
		} else {
			log.debug("----===="+file.getParent());
			createDir(targetSrc.substring(0,targetSrc.lastIndexOf("/")), false);
			uplocalFile(file);
		}
	}

	/**
	 * 
	 * <p> 上传单个文件:</p>
	 * 
	 * @param sourceSrc
	 *            原文件
	 * @param
	 * @author 
	 * @return void
	 * @version 1.0
	 */
	private void uplocalFile(File file) throws FileNotFoundException, IOException {
		//log.debug("上传的文件【" + file.getAbsolutePath() + "】");
		RandomAccessFile source = new RandomAccessFile(file, "r");
		source.seek(0);
		DataOutputStream os = null;
		TelnetOutputStream target = null;
		int ch;
		target = client.put(file.getName());
		os = new DataOutputStream(target);
		byte[] buf = new byte[10240];
		while ((ch = source.read(buf)) != -1) {
			os.write(buf,0,ch);
		}
		
		
	/*	while (source.getFilePointer() < source.length()) {
			ch = source.read();
			os.write(ch);
		}*/
		os.close();
		target.close();
		source.close();
	}

	/**
	 * 关闭ftp服务
	 * 
	 * @throws IOException
	 */
	public void closeFtp() throws IOException {
		if (null != client) {
			log.debug("与主机" + client.getUseFtpProxy() + "连接已断开!");
			client.closeServer();

		}
	}

	/**
	 * 建立FTP文件夹
	 * 
	 * @param d
	 * @param isDeep
	 * @return
	 */
	private boolean createDir(String d, boolean isDeep) {
		boolean success = true;

		if (isDeep) {
			try {

				client.cd(d);
				//log.debug("目录【" + d + "】存在!");
			} catch (IOException e) {
				//log.debug("目录【" + d + "】不存在,开始创建...");
				client.sendServer("mkd " + d + "\r\n");
				try {
					client.cd(d);
					client.binary();
					client.readServerResponse();
				} catch (IOException e1) {
					e.printStackTrace();
					success = false;
				}
			}
			return success;
		} else {
			//log.debug("开始创建文件夹【" + d + "】...");
			if (null == d && "".equals(d)) {
				success = false;
			}

			String[] dArray = d.split("/");
			for (int i = 0; i < dArray.length; i++) {
				if (null == dArray[i] || "".equals(dArray[i])) {
					continue;
				}
				//log.debug("验证子文件夹【" + dArray[i] + "】是否存在...");
				StringBuilder dir = new StringBuilder();
				dir.append(dArray[i]);
				if (!createDir(dArray[i].toString(), true)) {
					success = false;
					break;
				}
			}

		}
		return success;
	}

}

2.FtpBean

public class FtpBean {

		// ftp服务器地址
		private String hostName;

		//ftp服务器默认端口
		public static int defaultport = 21;

		// 登录名
		private String userName;

		// 登录密码
		private String password;

		// 需要访问的远程目录
		private String uploadDir="";
		
		private boolean isChTimeZone;

		public String getHostName() {
			return hostName;
		}

		public void setHostName(String hostName) {
			this.hostName = hostName;
		}

		public static int getDefaultport() {
			return defaultport;
		}

		public static void setDefaultport(int defaultport) {
			FtpBean.defaultport = defaultport;
		}

		public String getUserName() {
			return userName;
		}

		public void setUserName(String userName) {
			this.userName = userName;
		}

		public String getPassword() {
			return password;
		}

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

		public String getUploadDir() {
			return uploadDir;
		}

		public void setUploadDir(String uploadDir) {
			this.uploadDir = uploadDir;
		}

		public boolean isChTimeZone() {
			return isChTimeZone;
		}

		public void setChTimeZone(boolean isChTimeZone) {
			this.isChTimeZone = isChTimeZone;
		}

		public FtpBean(String hostName, String userName, String password) {
			super();
			this.hostName = hostName;
			this.userName = userName;
			this.password = password;
			
		}

		public FtpBean() {
			super();
		}


}


3.FTPclient

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import org.apache.log4j.Logger;
import sun.net.TelnetOutputStream;
import sun.net.TelnetInputStream;
import sun.net.ftp.FtpClient;


public class FTPclient {
	 
	private String localfilename;
	
	private String localSource;//ftp下载后存放的本地目录

	private String remotefilename;

	/**
	 * 日志
	 */
	private static final Logger log = Logger.getLogger( FTPclient.class.getName() );
	FtpClient ftpClient;

	// server:服务器名字
	// user:用户名
	// password:密码
	// path:服务器上的路径
	public void connectServer(String ip, int port,String user
	                , String password,String path) {

	try {
		
	ftpClient = new FtpClient();
	ftpClient.openServer(ip,port);
	ftpClient.login(user, password);
	log.info("ftpPaht="+ip+":" + "port:" + port +"login success!");
	if (path.length() != 0) ftpClient.cd(path);
	ftpClient.binary();
	} catch (IOException ex) {
	log.info("ftpPaht="+ip+":" + "port:" + port +"not login");
	log.info(ex);
	}
	}

	public void closeConnect() {
	try {
	ftpClient.closeServer();
	log.info("disconnect success");
	} catch (IOException ex) {
		log.info("not disconnect");
		log.info(ex);
	}
	}

	public void upload() {

		// this.localfilename = "D://test2//test.txt";
		// this.remotefilename = "test.txt";

		try {
			TelnetOutputStream os = ftpClient.put(this.remotefilename);
			java.io.File file_in = new java.io.File(this.localfilename);
			FileInputStream is = new FileInputStream(file_in);
			byte[] bytes = new byte[1024];
			int c;
			while ((c = is.read(bytes)) != -1) {
				os.write(bytes, 0, c);
			}
			log.info(localfilename + "upload success");
			is.close();
			os.close();
		} catch (IOException ex) {
			log.info(localfilename + "not upload");
			log.info(ex);
		}
	}
	
	
	public void download() {

	try {
			TelnetInputStream is = ftpClient.get(this.remotefilename);
			java.io.File file_in = new java.io.File(this.localfilename);
			FileOutputStream os = new FileOutputStream(file_in);
			byte[] bytes = new byte[1024];
			int c;
			while ((c = is.read(bytes)) != -1) {
				// System.out.println((char)is.read());
				// System.out.println(file_in);
				os.write(bytes, 0, c);
			}

			log.info(remotefilename + "download success");
			os.close();
			is.close();
		} catch (IOException ex) {
			log.info(remotefilename + "not download");
			log.info(ex);
		}
	}

	public void download(String remotePath,String remoteFile,String localFile) {

	try {
	if (remotePath.length() != 0) ftpClient.cd(remotePath);
	TelnetInputStream is = ftpClient.get(remoteFile);
	java.io.File file_in = new java.io.File(localFile);
	FileOutputStream os = new FileOutputStream(file_in);
	byte[] bytes = new byte[1024];
	int c;
	while ((c = is.read(bytes)) != -1) {
	// System.out.println((char)is.read());
	// System.out.println(file_in);
	os.write(bytes, 0, c);
	}

	log.info(remoteFile + "download success");
	os.close();
	is.close();
	} catch (IOException ex) {
		log.info(remoteFile + "not download");
		log.info(ex);
	}
	}

	public void download(String remoteFile,String localFile) {

	try {
	TelnetInputStream is = ftpClient.get(remoteFile);
	java.io.File file_in = new java.io.File(localFile);
	FileOutputStream os = new FileOutputStream(file_in);
	byte[] bytes = new byte[1024];
	int c;
	while ((c = is.read(bytes)) != -1) {
	// System.out.println((char)is.read());
	// System.out.println(file_in);
	os.write(bytes, 0, c);
	}

	log.info(remoteFile + "download success");
	os.close();
	is.close();
	} catch (IOException ex) {
		log.info(remoteFile + "not download");
		log.info(ex);
	}
	}

	public void makeDirectory(String ftpdirectory) throws IOException{

		try
		{
			char ch = ' ';
			if (ftpdirectory.length() > 0)
				ch = ftpdirectory.charAt(ftpdirectory.length() - 1);
			for (; ch == '/' || ch == '\\'; ch = ftpdirectory.charAt(ftpdirectory.length() - 1))
				ftpdirectory = ftpdirectory.substring(0, ftpdirectory.length() - 1);

			int slashindex = ftpdirectory.indexOf(47);
			int backslashindex = ftpdirectory.indexOf(92);
			int index = slashindex;
			String dirall = ftpdirectory;
			if (backslashindex != -1 && (index == -1 || index > backslashindex))
				index = backslashindex;
			String directory = "";
			while (index != -1) {
				if (index > 0) {
					String dir = dirall.substring(0, index);
					directory = directory + "/" + dir;
					ftpClient.sendServer("xmkd " + directory + "\r\n");
					ftpClient.readServerResponse();
				}
				dirall = dirall.substring(index + 1);
				slashindex = dirall.indexOf(47);
				backslashindex = dirall.indexOf(92);
				index = slashindex;
				if (backslashindex != -1 && (index == -1 || index > backslashindex))
					index = backslashindex;
			}
			ftpClient.sendServer("xmkd " + ftpdirectory + "\r\n");
			ftpClient.readServerResponse();
		}
		catch(Exception e)
		{
			e.printStackTrace();

		}
	}
	public static void main(String agrs[]) {

	String filepath[] = { "/callcenter/index.jsp", "/callcenter/ip.txt",
	"/callcenter/mainframe/image/processing_bar_2.gif",
	"/callcenter/mainframe/image/logo_01.jpg" };
	String localfilepath[] = { "C:\\FTP_Test\\index.jsp",
	"C:\\FTP_Test\\ip.txt", "C:\\FTP_Test\\processing_bar_2.gif",
	"C:\\FTP_Test\\logo_01.jpg" };

	FTPclient fu = new FTPclient();
	fu.connectServer("172.16.1.66",22, "web_test", "123456","/callcenter");
	for(int i=0;i<filepath.length;i++){
	fu.download(filepath[i],localfilepath[i]);
	}

	// fu.upload();
	// fu.download();
	fu.closeConnect();

	}

	public String getLocalfilename() {
		return localfilename;
	}

	public void setLocalfilename(String localfilename) {
		this.localfilename = localfilename;
	}

	public String getRemotefilename() {
		return remotefilename;
	}

	public void setRemotefilename(String remotefilename) {
		this.remotefilename = remotefilename;
	}

	public String getLocalSource() {
		return localSource;
	}

	public void setLocalSource(String localSource) {
		this.localSource = localSource;
	}
}



posted @ 2017-04-26 09:24  御前提笔小书童  阅读(303)  评论(0编辑  收藏  举报