Java saves a file with special characters in the file name

I have a problem with the encoding of Java files.

I have a Java program that will save the input stream as a file with the given file name, the code fragment looks like this:

File out = new File(strFileName);
Files.copy(inStream, out.toPath());

It works fine in Windows if the file name does not contain special characters, such as Ö, with these characters in the file name, the saved file displays a malformed file name in Windows.

I understand that with the JVM option -Dfile.encoding=UTF-8this problem can be fixed, but I will have a solution in my code, and not ask all my users to change their JVM settings.

While debugging the program, I see that the file name string always shows the correct character, so I assume that the problem is not in the internal encoding.

Can anyone explain what went wrong behind the stage? and is there any way to avoid this problem programmatically? I tried to get bytes from the string and change the encoding, but it does not work.

Thank.

+4
source share
1 answer

Using the URLEncoder class will work:

String name = URLEncoder.encode("fileName#", "UTF-8");
File output = new File(name);
0
source

Source: https://habr.com/ru/post/1670380/


All Articles