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无关。

我使用了相同的代码,并以不同的方式使用了Run Configuration,如下所示,

java - 无法将中文字符写入文件名-LMLPHP

现在,在运行程序之后,我在控制台中获得了以下输出,

Exception in thread "main" java.io.FileNotFoundException: C:\temp\??.txt (The filename, directory name, 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将无法从控制台正确读取那些字符,并且您将??作为filename

请坚决更改控制台的字符编码,我坚信您正在使用某些IDE。可能是您已更改,或者您的控制台继承了字符编码,而该字符编码不应该编码这些字符。

10-01 02:38
查看更多