Java saves the file using special characters in the file name
I have a problem with java file coding
I have a java program that saves the input stream as a file with a given file name. The code snippet is as follows:
File out = new File(strFileName); Files.copy(inStream,out.toPath());
It works normally on windows. Unless the file name contains some special characters, such as Ö, these characters are included in the file name, the saved file will display the garbled file name on windows
I understand by applying the JVM option - dfile Encoding = UTF-8 can solve this problem, but I will find a solution in my code instead of asking all my users to change their JVM options
When debugging the program, I can see that the file name string always displays the correct characters, so I guess the problem is not internal coding
Can anyone explain what's wrong behind the scenes? Is there any way to avoid this problem programmatically? I tried to get bytes from the string and change the encoding, but it didn't work
thank you.
Solution
You can work with urlencoder class:
String name = URLEncoder.encode("fileName#","UTF-8"); File output = new File(name);