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
使用上面的代码,它对于英文字符工作得很好,但对于中文字符则不行。
我在这里遵循了答案:如何用Java编写UTF-8文件? https://stackoverflow.com/questions/1001540/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)
使用蔚来:
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();
Stack:
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)