最近一個項目要用到FTP做上傳下載,我訪問ftp的url中有中文名稱,結果每次都報如下錯:
1 Exception in thread "main" java.lang.IllegalArgumentException
2 at sun.net.www.ParseUtil.decode(Unknown Source)
3 at sun.net.www.protocol.ftp.FtpURLConnection.decodePath(Unknown Source)
4 at sun.net.www.protocol.ftp.FtpURLConnection.getInputStream(Unknown Source)
5 at URLConnectionDownloader.download(URLConnectionDownloader.java:33)
6 at URLConnectionDownloader.main(URLConnectionDownloader.java:15)
本來可以用apache的FtpClient解決這個問題,但是我不太想用那種方式,我想省點步驟。所以堅持用
URL url = new URL("ftp://xxxx:1234@192.168.1.101:21/測試/測試.jpg");這種方式,網上搜了一大堆資料,基本都是說編碼問題的。用了java.net.xxx自帶轉碼的工具也沒用,嘗試了各種iso8859-1、GBK、UTF-8編碼,依然無效。
最后發現windows的ftp服務器,是用gbk來處理的,linux的是utf-8,原來只需要在訪問ftp前設置一下系統編碼就OK了,下面放代碼:
System.setProperty("file.encoding", "GBK"); URL url = new URL("ftp://xxxx:1234@192.168.1.101:21/測試/測試.jpg"); is =url.openConnection().getInputStream(); output = response.getOutputStream(); byte[] buffer = new byte[4096]; int count = 0; while ((count = is.read(buffer)) > 0) { output.write(buffer, 0, count); } output.flush(); response.flushBuffer(); is.close();
到此就算OK了,用了這個就不要再去給你的路徑轉碼了,不然會導致讀取失敗!
2015-04-08 PS:時隔三年回來看這篇博客,感覺自己簡直是個逗比,直接把FTP的用戶和密碼暴漏給了前台,如果我現在寫的話,會經過服務器中轉后才展示出來。當年剛入行,年輕啊。。。。