读取配置文件连接ftp代码实现本地下载

/***
 * Ftp 文件下载类
 * @author ***
 */
public class FtpDownload {
	/***
	 * 获取 FtpClient
	 * @param refID
	 * @return
	 */
	public FtpClient connectServer() {
		FtpClient ftpClient = new FtpClient();
		FtpInfo ftpInfo = getFtpInfo();
		try {
			if (ftpInfo.getPort() != -1) {
				ftpClient.openServer(ftpInfo.getHost(), ftpInfo.getPort());
			} else {
				ftpClient.openServer(ftpInfo.getHost());
			}
			ftpClient.login(ftpInfo.getFtpUser(), ftpInfo.getFtpPwd());
		} catch (Exception e) {
			System.out.print("clientFtp exception"+e.getMessage());
		}
		return ftpClient;
	}
	
	/**
	 * 获取ftp信息
	 * @param path
	 * @return
	 */
	public FtpInfo getFtpInfo(String path) {
		//读取 ftpServer.properties 文件的 value 文件目录在  classes 目录下
		ResourceBundle resource = ResourceBundle.getBundle("ftpServer");
		FtpInfo ftp = new FtpInfo();
		ftp.setHost(resource.getString("middle_ftpPath"));  
		ftp.setFtpUser(resource.getString("middle_user"));
		ftp.setFtpPwd(resource.getString("middle_password"));
		ftp.setPort(21);
		ftp.setDirName(resource.getString("middle_dir"));
		return ftp;	
	}

	/**
	 * 下载文件
	 * @param ftpClient
	 * @param remotePath
	 * @param localPath
	 * @param filename
	 * @return
	 * @throws Exception
	 */
	public int downloadFile(FtpClient ftpClient, String remotePath,
			String localPath, String filename) throws Exception {
		int isExistInt = 0;
		try {
			//目录切换到远程的
			if (remotePath.length() != 0) {
				try {
					ftpClient.cd(remotePath);
				} catch (Exception ex) {
					System.out.print("ftpClient.cd(remotePath) Exception:"
							+ ex.getMessage());
				}
			}
			ftpClient.binary();
			//获得文件 的输入 流
			TelnetInputStream is = ftpClient.get(filename);
			//创建磁盘目录
			File file = new File(localPath);
			if (!file.exists()) {
				file.mkdirs();
			}
			//File file_out = new File(localPath + File.separator + filename);
			//在创建的目录中新建个文件
			File file_out = new File(file, filename);
			FileOutputStream os = new FileOutputStream(file_out);
			byte[] bytes = new byte[1024];
			int c;
			while ((c = is.read(bytes)) != -1) {
				os.write(bytes, 0, c);
			}
			is.close();
			os.close();
			isExistInt = 1;
		} catch (Exception ex) {
			System.out.print("download FTP file exception"+e.getMessage());
		}
		return isExistInt;
	}
}

[color=olive][/color]

你可能感兴趣的:(读取配置文件连接ftp代码实现本地下载)