java – 无法将中文字符写入文件名
发布时间:2020-12-15 00:49:02 所属栏目:Java 来源:网络整理
导读:public static void main(String[] args) throws IOException{ Scanner in = new Scanner(System.in); String fileName = in.nextLine(); Writer out = new BufferedWriter(new OutputStreamWriter( new FileOutputStream("C:/temp/"+fileName+".txt"),"UTF-
public static void main(String[] args) throws IOException { Scanner in = new Scanner(System.in); String fileName = in.nextLine(); Writer out = new BufferedWriter(new OutputStreamWriter( new FileOutputStream("C:/temp/"+fileName+".txt"),"UTF-8"));//Ex thrown out.close(); } 我正在尝试创建一个可以处理中文字符到文件名的编写器.所以我可以创建一个名为你好.txt的文件. 但是我得到了一个带有上述代码的FileNotFoundException,它对英文字符完全正常,但不适用于中文字符. 我按照这里的答案:How to write a UTF-8 file with Java?生成上面的代码,但它不起作用. 任何人都知道如何实现这一目标? 堆栈跟踪: Exception in thread "main" java.io.FileNotFoundException: C:temp??.txt (The filename,directory name,or volume label syntax is incorrect) at java.io.FileOutputStream.open0(Native Method) at java.io.FileOutputStream.open(Unknown Source) at java.io.FileOutputStream.<init>(Unknown Source) at java.io.FileOutputStream.<init>(Unknown Source) 使用NIO: Path path = Paths.get("C:/temp/"+fileName+".txt");//throws ex Charset charset = Charset.forName("UTF-8"); Path file = Files.createFile(path); BufferedWriter bufferedWriter = Files.newBufferedWriter(file,charset); bufferedWriter.close(); 堆: Exception in thread "main" java.nio.file.InvalidPathException: Illegal char <?> at index 8: C:/temp/?.txt at sun.nio.fs.WindowsPathParser.normalize(Unknown Source) at sun.nio.fs.WindowsPathParser.parse(Unknown Source) at sun.nio.fs.WindowsPathParser.parse(Unknown Source) at sun.nio.fs.WindowsPath.parse(Unknown Source) at sun.nio.fs.WindowsFileSystem.getPath(Unknown Source) at java.nio.file.Paths.get(Unknown Source) 解决方法
我发现这个问题与eclipse控制台的字符编码有关,与Java无关.
我使用了相同的代码,并使用不同的运行配置,如下所示, 现在运行程序后,我在控制台中得到了以下输出, Exception in thread "main" java.io.FileNotFoundException: C:temp??.txt (The filename,or volume label syntax is incorrect) at java.io.FileOutputStream.open(Native Method) at java.io.FileOutputStream.<init>(FileOutputStream.java:206) at java.io.FileOutputStream.<init>(FileOutputStream.java:95) at Test.main(Test.java:21) 结论:对于运行配置中的ISO-8859-1编码,Scanner将无法从控制台正确读取这些字符,因为控制台具有不同的字符编码,您将拥有?作为文件名. 请更改控制台的字符编码,我坚信您正在使用某些IDE.可能是您已更改或您的控制台继承了字符编码,而不是编码这些字符. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |