Special characters in filename java

限于喜欢 提交于 2020-01-04 12:48:32

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!