天天看点

通过FTP从服务器上下载文件

1.鍏堣缃ソFTP鏈嶅姟鍣ㄥ湴鍧€銆佺鍙c€佹湇鍔″櫒鏂囦欢瀛樻斁璺緞銆佹枃浠舵湰鍦板瓨鍌ㄨ矾寰勩€佺敤鎴跺悕鍜屽瘑纰?鎴戣繖閲岃幏鍙栫殑鏄湇鍔″櫒鏍圭洰褰曚笅褰撳ぉ鏃ユ湡 (鈥測yyy-mm-dd鈥? 鐨勬枃浠跺す)

Date now = new Date();
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		String date = dateFormat.format(now);
		String FTP_PATH = "/"+date;  //鏈嶅姟鍣ㄦ枃浠朵繚瀛樿矾寰?		String FTPHost = "";//鏈嶅姟鍣ㄥ湴鍧€
		Integer prot = 21;//FTP浼犺緭榛樿绔彛21
		String userName = "鐢ㄦ埛鍚?
		String userPassword = "瀵嗙爜";
		String localPath = "F:\寮€鍙戞枃妗?;
           

2.鑾峰彇鏂囦欢鍚嶄箣鍚庡皢鏂囦欢杞崲鎴愬瓧鑺備笅杞藉埌鏈湴

try {
	List<String> list=getFileList(FTP_PATH,FTPHost,prot,userName,userPassword);
		for (int i = 0; i <list.size(); i++) {
			File file=new File(localPath );
			file.mkdir();
			if(file.isDirectory()) {
			String name=list.get(i);
			//涓嬭浇鏂囦欢
			downloadFtpFile(FTPHost,userName,userPassword,prot,FTP_PATH,localPath,name);
			logger.debug((localPath+"\\"+name));
			}
		}
}catch (Exception e) {
			logger.debug("FTP涓嬭浇澶辫触锛?+e.getMessage());
	}
           

鑾峰彇鎸囧畾璺緞涓嬫枃浠跺悕

public List<String> getFileList(String path,String ftpHost, int ftpPort, String ftpUserName, String ftpPassword) throws Exception {
		List<String> fileLists = new ArrayList<String>();
		// 鑾峰緱鎸囧畾鐩綍涓嬫墍鏈夋枃浠跺悕
		FTPFile[] ftpFiles = null;
		//杩炴帴鏈嶅姟鍣?		FTPClient ftpClient=getFTPClient(ftpHost, ftpPort, ftpUserName, ftpPassword);
		try {
			ftpFiles = ftpClient.listFiles(path);
		} catch (IOException e) {
			e.printStackTrace();
		}
		for (int i = 0; ftpFiles != null && i < ftpFiles.length; i++) {
			FTPFile file = ftpFiles[i];
			if (file.isFile()) {

				String name=new String(file.getName().getBytes("iso-8859-1"),"GBK");
				logger.debug(name);
				fileLists.add(name);
			}
		}
		return fileLists; 
	}
           

杩炴帴FTP鏈嶅姟鍣?

public static FTPClient getFTPClient(String ftpHost, int ftpPort, String ftpUserName, String ftpPassword) {
		FTPClient ftpClient = null;
		try {
			ftpClient = new FTPClient();
			ftpClient.connect(ftpHost, ftpPort);// 杩炴帴FTP鏈嶅姟鍣?			ftpClient.login(ftpUserName, ftpPassword);// 鐧婚檰FTP鏈嶅姟鍣?			if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
				logger.info("鏈繛鎺ュ埌FTP锛岀敤鎴峰悕鎴栧瘑鐮侀敊璇€?);
				ftpClient.disconnect();
			} else {
				logger.info("FTP杩炴帴鎴愬姛銆?);
			}
		} catch (SocketException e) {
			e.printStackTrace();
			logger.info("FTP鐨処P鍦板潃鍙兘閿欒锛岃姝g‘閰嶇疆銆?);
		} catch (IOException e) {
			e.printStackTrace();
			logger.info("FTP鐨勭鍙i敊璇?璇锋纭厤缃€?);
		}
		return ftpClient;
	}
           

浠巉tp涓婁笅杞芥枃浠?

public static void downloadFtpFile(String ftpHost, String ftpUserName, String ftpPassword, int ftpPort,
			String ftpPath, String localPath, String fileName) {

		String localCharset = "GBK";//鏈湴缂栫爜
		String serverCharset = "ISO-8859-1";//鏈嶅姟鍣ㄧ紪鐮?		FTPClient ftpClient = null;

		try {
			ftpClient = getFTPClient(ftpHost, ftpPort, ftpUserName, ftpPassword);
			// 璁剧疆涓婁紶鏂囦欢鐨勭被鍨嬩负浜岃繘鍒剁被鍨?			if (FTPReply.isPositiveCompletion(ftpClient.sendCommand("OPTS UTF8", "ON"))) {// 寮€鍚湇鍔″櫒瀵筓TF-8鐨勬敮鎸侊紝濡傛灉鏈嶅姟鍣ㄦ敮鎸佸氨鐢║TF-8缂栫爜锛屽惁鍒欏氨浣跨敤鏈湴缂栫爜锛圙BK锛?
				FtpConfig.LOCAL_CHARSET = "UTF-8";
			}
			ftpClient.setControlEncoding(FtpConfig.LOCAL_CHARSET);
			ftpClient.enterLocalPassiveMode();// 璁剧疆琚姩妯″紡
			ftpClient.setFileType(FTP.BINARY_FILE_TYPE);// 璁剧疆浼犺緭鐨勬ā寮?			// 涓婁紶鏂囦欢
			//瀵逛腑鏂囨枃浠跺悕杩涜杞爜锛屽惁鍒欎腑鏂囧悕绉扮殑鏂囦欢涓嬭浇澶辫触
			String fileNameTemp = new String(fileName.getBytes(localCharset), serverCharset);
			ftpClient.changeWorkingDirectory(ftpPath);

			InputStream retrieveFileStream = ftpClient.retrieveFileStream(fileNameTemp);
			byte[] input2byte = input2byte(retrieveFileStream);
			byte2File(input2byte, localPath, fileName);

			if(null != retrieveFileStream){
				retrieveFileStream.close();
			}
		} catch (FileNotFoundException e) {
			logger.error("娌℃湁鎵惧埌" + ftpPath + "鏂囦欢");
			e.printStackTrace();
		} catch (SocketException e) {
			logger.error("杩炴帴FTP澶辫触.");
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
			logger.error("鏂囦欢璇诲彇閿欒銆?);
			e.printStackTrace();
		} finally {

			if (ftpClient.isConnected()) {
				try {
					//閫€鍑虹櫥褰?					ftpClient.logout();
					//鍏抽棴杩炴帴
					ftpClient.disconnect(); 
				} catch (IOException e) {
				}
			}
		}
	}
           

灏嗘祦杞崲涓哄瓧鑺傛暟缁?

// 灏嗚緭鍏ユ祦杞负byte[]
	public static final byte[] input2byte(InputStream inStream) throws IOException {
		ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
		byte[] buff = new byte[100];
		int rc = 0;
		while ((rc = inStream.read(buff, 0, 100)) > 0) {
			swapStream.write(buff, 0, rc);
		}
		byte[] in2b = swapStream.toByteArray();
		return in2b;
	}
           

灏嗗瓧鑺傛暟缁勮浆鎹负鏂囦欢

// 灏哹yte[]杞负鏂囦欢
	public static void byte2File(byte[] buf, String filePath, String fileName) {
		BufferedOutputStream bos = null;
		FileOutputStream fos = null;
		File file = null;
		try {
			File dir = new File(filePath);
			if (!dir.exists() && dir.isDirectory()) {
				dir.mkdirs();
			}
			file = new File(filePath + File.separator + fileName);
			fos = new FileOutputStream(file);
			bos = new BufferedOutputStream(fos);
			bos.write(buf);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (bos != null) {
				try {
					bos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (fos != null) {
				try {
					fos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}