文件名Java中的特殊字符 [英] Special characters in filename java

查看:713
本文介绍了文件名Java中的特殊字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在文件名中写入带有特殊字符的文件,例如téééê.mp3",但文件名始终保留?"而不是字符é",我尝试了几种方法,但没有找到解决方法:

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();

我也尝试过这种方式.

OutputStreamWriter bw = new OutputStreamWriter(new FileOutputStream(URLDecoder.decode(FILE_PATH+"musics/tééé ê.mp3", "UTF-8")), "UTF-8");
bw.write(data);
bw.close();

推荐答案

尝试使用Files:

final Path target = Paths.get("tééé ê.mp3");

try (
    final OutputStream out = Files.newOutputStream(target, StandardOpenOption.CREATE_NEW);
) {
    // write
}

现在,如果这是您的文件系统不支持此类文件名的问题,您将得到一个InvalidPathException;与File不同,新API拒绝创建可能最终无法读取的文件名.

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.

请注意,InvalidPathException未选中 ;因此,您必须明确捕获此异常.另外请注意,如果JVM使用的当前字符编码不适合生成文件名,则可能会出现此异常.

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.

这篇关于文件名Java中的特殊字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆