Kiran
Kiran

Reputation: 3361

Unable to read from file name in java which contains internationalized characters in its path

It works fine if the same file is selected with JFileChooser dialog

Path is something like C:\テスト\sample.txt

The following code does not work

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

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

It fails with FileNotFoundException

Upvotes: 4

Views: 1235

Answers (2)

Kiran
Kiran

Reputation: 3361

Thanks a lot for the help. The following change has resolved the problem apart from your solutions

...
File file = new File(new String(teststring.getBytes(),"utf8");
...

Upvotes: 2

beny23
beny23

Reputation: 35008

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 テスト

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!

Upvotes: 8

Related Questions