Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

file

ascii

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

like image 935
Kiran Avatar asked Dec 28 '22 03:12

Kiran


1 Answers

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!

like image 115
beny23 Avatar answered Jan 25 '23 13:01

beny23