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();
}
I'm trying to create a writer that can handle chinese characters to the file name. So I can create a file called 你好.txt
for example.
However I get a FileNotFoundException
with the above code, it works perfectly fine for English characters but not with Chinese characters.
I followed the answers here: How to write a UTF-8 file with Java? to produce the above code but it doesn't work.
Anyone know how can I accomplish this?
Stack Trace:
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)
Using 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();
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)