简体   繁体   中英

Java File with filename in UTF-8

I'm writing a web application running on Tomcat.

Within this web application I want to create/save files like this:

File destFile = new File(path + "/" + fileName);
destFile.createNewFile();

Now the tricky thing is that the fileName is a UTF-8 encoded string. Unfortunately all UTF-8 characters such as German umlauts get replaced by "?" in the name of the file which is actually created.

So a fileName "hellö.txt" ends as "hell?.txt".

How can I fix this?

I'm running on a Ubuntu 14.04 server and as far as I can see everything is setup to support UTF-8.

I already added -Dfile.encoding=UTF8 to the JAVA_OPTS but this did not help.

Cheers.

Solved!

In my case it was not a Java bug. Instead, the locale settings on my server were broken. After fixing this like described here https://askubuntu.com/questions/162391/how-do-i-fix-my-locale-issue it is now working even with java.io.File .

Even when it's possible, which I am not sure about, it's a really bad practice to include characters like 'ö', 'ä' in file names. Instead, you should replace them with their synonyms 'oe' or 'ae'.

I wrote a basic function to do this for "german umlauts"

string removeBadCharacters(String string) {
    string = string.replace("ö", "oe");
    string = string.replace("ä", "ae");
    string = string.replace("ü", "ue");
    string = string.replace("ß", "ss");
    return string;
}

Yould then just pass your fileName and use the formatted string:

File destFile = new File(path + "/" + removeBadCharacters(fileName));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM