![](/img/trans.png)
[英]FileUtils.readFileToString() from Apache Commons IO works incorrectly with Cyrillic
[英]org.apache.commons.io.FileUtils.readFileToString and blanks in filepath
我正在嘗試在 Windows 7 上使用 org.apache.commons.io 2.4 版將文件讀取為字符串。
String protocol = url.getProtocol();
if(protocol.equals("file")) {
File file = new File(url.getPath());
String str = FileUtils.readFileToString(file);
}
但它失敗了:
java.io.FileNotFoundException: File 'C:\workspace\project\resources\test%20folder\test.txt' does not exist
但如果我這樣做:
String protocol = url.getProtocol();
if(protocol.equals("file")) {
File file = new File("C:\\workspace\\resources\\test folder\\test.txt");
String str = FileUtils.readFileToString(file);
}
我工作正常。 因此,當我手動輸入帶有空格/空白的路徑時,它可以工作,但是當我從 url 創建它時,它卻沒有。
我錯過了什么?
試試這個:
File file = new File(url.toURI())
順便說一句,既然您已經在使用 Apache Commons IO(對您有好處!),為什么不處理流而不是文件和路徑呢?
IOUtils.toString(url.openStream(), "UTF-8");
我正在使用IOUtils.toString(InputStream, String)
。 請注意,我顯式傳遞編碼以避免操作系統依賴性。 你也應該這樣做:
String str = FileUtils.readFileToString(file, "UTF-8");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.