4

如果使用 JFileChooser 对话框选择相同的文件,它工作正常

路径类似于 C:\テスト\sample.txt

以下代码不起作用

    String teststring = "C:\\テスト\\sample.txt";
    File file = new File(teststring);

    BufferedReader reader = new BufferedReader(new FileReader(file));
    System.out.println(reader.readLine());
    ...

它因 FileNotFoundException 而失败

4

2 回答 2

8

The problem is most likely that when Java compiled, it was compiling in an encoding that did not match the file encoding for the テスト characters. You can check that by inserting

 System.out.println(teststring);

which will probably not print テスト</p>

Per default, the encoding is the platform encoding. If your file is saved as UTF-8, you could compile with

javac -encoding UTF-8 YourClass.java

(or use the encoding="UTF-8" attribute for your <javac> task in Ant

EDIT:

And as @assylias pointed out, backslashes need to be escaped!

于 2012-04-05T12:42:11.177 回答
2

非常感谢您的帮助。除了您的解决方案之外,以下更改已解决问题

...
File file = new File(new String(teststring.getBytes(),"utf8");
...
于 2012-04-09T14:01:55.180 回答