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,它对英文字符完全正常,但不适用于中文字符.
任何人都知道如何实现这一目标?
堆栈跟踪:
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.(Unknown Source)
at java.io.FileOutputStream.(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)