最近需要通過org.apache.commons.net,從服務器讀取一系列文件信息,發現遇到了一個詭異的問題,
1 public static String downloadFile() throws Exception{ 2 { 3 FTPClient ftp = new FTPClient(); 4 ftp.connect("xxx.xxx.xxx.xxx", 21); 5 ftp.login("xx", "xx"); 6 if (ftp.isConnected()) { 7 String dir = ftp.printWorkingDirectory(); 8 ftp.cwd("/pcf/"); 9 dir = ftp.printWorkingDirectory(); 10 System.out.println(dir); 11 return Arrays.toString(ftp.listNames (dir)); 12 } else { 13 return "error"; 14 } 15 }
在運行的11行時,報了出了一個異常Exception in thread "main" java.net.SocketException: Software caused connection abort: socket write error,百度之,未能找到解決辦法。然后上網檢索FTPClient使用的示例代碼,發現在示例中,登陸后需要設置被動模式
1 public static String downloadFile() throws Exception 2 { 3 FTPClient ftp = new FTPClient(); 4 ftp.connect("xxx.xxx.xxx.xxx", 21); 5 ftp.login("xx", "xxx"); 6 if (ftp.isConnected()) { 7 System.out.println(ftp.getReplyCode()); 8 String dir = ftp.printWorkingDirectory(); 9 System.out.println(dir); 10 ftp.cwd("/pcf/"); 11 dir = ftp.printWorkingDirectory(); 12 System.out.println(dir); 13 ftp.enterLocalPassiveMode();//設為被動模式 14 ftp.setFileType(FTP.BINARY_FILE_TYPE); //不設為二進制傳送模式,會收不到0x0D 15 return Arrays.toString(ftp.listNames (dir)); 16 } else { 17 return "error"; 18 } 19 }
這時異常還是存在,但改變為 Exception in thread "main" java.net.SocketException: Permission denied: recv failed。
通過百度發現,如圖搜索結果中的軟件,在他的FAQ中提到,這是由於java7的bug,導致與win7防火牆不兼容導致。
再從百度中搜索,java7+ FTP,就可以發現許多對於此問題的解決方法。我直接將我的編譯環境設置到 java 6 ,我的第一段代碼就能正常使用了,特此記錄!