1. 程式人生 > >從ftp上讀取.csv檔案遇到的兩個問題。

從ftp上讀取.csv檔案遇到的兩個問題。

		FTPClient ftp = new FTPClient();	
		InputStream fis = null;
		try{
			int reply;
			ftp.connect(url);
			// 如果採用預設埠,可以使用ftp.connect(url)的方式直接連線FTP伺服器
			ftp.login(username, password);// 登入
			ftp.setControlEncoding("utf-8");
			reply = ftp.getReplyCode();
			if (!FTPReply.isPositiveCompletion(reply)) {
				ftp.disconnect();
				logger.info("CommissionDealJob........reply="+reply);
			}
			ftp.changeWorkingDirectory(remotePath);// 轉移到FTP伺服器目錄
			FTPFile[] fs = ftp.listFiles();
			String date = yyyyMM.format(new Date());
			String fileTime = "list_"+date+"_2.csv";//檔名稱前的時間(前一天日期)		
			logger.info("在伺服器查詢檔案:"+fileTime);
			for (FTPFile ff : fs) {
				if(ff != null){
					String fname  = ff.getName();
					if(ff.isDirectory()){
						logger.info(fname + "是資料夾" );
						continue;
					}
					if(fname.indexOf(fileTime) >= 0) {
						logger.info("檔名稱:" + fname);
						fis = ftp.retrieveFileStream(fname);
						BufferedReader reader = new BufferedReader(new InputStreamReader(fis, "GBK"));
						reader.readLine();//第一行是標題頭
						String line = null;
						int i = 0;
						while ((line = reader.readLine()) != null) {								
							String item[] = line.split(",");
						}				
						fis.close();
					}//同步檔案存在
				}//伺服器目錄下有檔案
			}
			ftp.changeToParentDirectory();//返回到wotv_settlement目錄
			ftp.changeToParentDirectory();//返回到根目錄
			ftp.changeWorkingDirectory(sanwuPath);// 轉移到FTP伺服器目錄
			fs = ftp.listFiles();
			String sanwuFileName = "s"+date+".txt";
			logger.info("在伺服器查詢檔案:"+sanwuFileName);
			for (FTPFile ff : fs) {
				String fname  = ff.getName();
				if(ff.isDirectory()){
					logger.info(fname + "是資料夾" );
					continue;
				}
				if(fname.indexOf(sanwuFileName) >= 0) {
					logger.info("檔名稱:" + fname);
					fis = ftp.retrieveFileStream(fname);
					BufferedReader reader = new BufferedReader(new InputStreamReader(fis, "GBK"));
					String line = null;
					int i = 0;
					while ((line = reader.readLine()) != null) {
						String item[] = line.split(",");
					}	
				}
			}
		}catch(Exception e){
			e.printStackTrace();
			logger.error("處理沃視訊同步檔案異常"+e.getMessage(), e);
		}finally{
			try{
				if(fis!=null){
					fis.close();
				}
			}catch(Exception e){
				e.printStackTrace();
				logger.error("關閉連線異常"+e.getMessage(), e);
			}					
		}
	

1、程式碼如上,遇到的第一個問題是連線不上ftp,賬號密碼地址正確。報錯如下

java.net.SocketException: Software caused connection abort: socket write error  

百度之:解答是關閉防火牆,百度下關閉防火牆步驟,關閉。

2、在ftp上如何切換到同級目錄。

首先讀取了檔案要先關閉讀取的流

fis.close();

其次:A-B是同級目錄。進入到A目錄下,更換到B目錄。要返回兩次上級目錄。

即:ftp.changeToParentDirectory();執行兩次。