问题
I'm trying to write a file with special characters in filename, for examplo "tééé ê.mp3", but the filename always stay with "?" instead the character "é", I tried a several methods but i didn't found a solution:
String musicName = new String("tééé ê.mp3".getBytes(), "UTF-8");
OutputStreamWriter bw = new OutputStreamWriter(new FileOutputStream(FILE_PATH+"musics/"+musicName), "UTF-8");
bw.write(data);
bw.close();
I tried this way too.
OutputStreamWriter bw = new OutputStreamWriter(new FileOutputStream(URLDecoder.decode(FILE_PATH+"musics/tééé ê.mp3", "UTF-8")), "UTF-8");
bw.write(data);
bw.close();
回答1:
Try with Files
:
final Path target = Paths.get("tééé ê.mp3");
try (
final OutputStream out = Files.newOutputStream(target, StandardOpenOption.CREATE_NEW);
) {
// write
}
Now, if this is a problem that your filesystem does not support such filenames, you will get an InvalidPathException
; unlike File
, the new API refuses to create file names which may end up being unreadable.
If this is the case that you can indeed not create the path, well, you'll have to find a way to escape and unescape somewhat; maybe write an alternate name to some sort of database or something.
Note that InvalidPathException
is unchecked; you therefore have to catch this exception explicitly. Also note that you may get this exception if the current character coding used by the JVM is just not suitable to generate the filename.
来源:https://stackoverflow.com/questions/28476663/special-characters-in-filename-java