java - Cannot write chinese characters to a filename -
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 create writer can handle chinese characters file name. can create file called 你好.txt
example.
however filenotfoundexception
above code, works fine english characters not chinese characters.
i followed answers here: how write utf-8 file java? produce above code doesn't work.
anyone know how can accomplish this?
stack trace:
exception in thread "main" java.io.filenotfoundexception: c:\temp\??.txt (the filename, directory name, or volume label syntax incorrect) @ java.io.fileoutputstream.open0(native method) @ java.io.fileoutputstream.open(unknown source) @ java.io.fileoutputstream.<init>(unknown source) @ 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 <?> @ index 8: c:/temp/?.txt @ sun.nio.fs.windowspathparser.normalize(unknown source) @ sun.nio.fs.windowspathparser.parse(unknown source) @ sun.nio.fs.windowspathparser.parse(unknown source) @ sun.nio.fs.windowspath.parse(unknown source) @ sun.nio.fs.windowsfilesystem.getpath(unknown source) @ java.nio.file.paths.get(unknown source)
i have found out problem related character encoding of eclipse console , not related java
.
i have used same code , used run configuration
differently shown below,
now after running program got following output in console,
exception in thread "main" java.io.filenotfoundexception: c:\temp\??.txt (the filename, directory name, or volume label syntax incorrect) @ java.io.fileoutputstream.open(native method) @ java.io.fileoutputstream.<init>(fileoutputstream.java:206) @ java.io.fileoutputstream.<init>(fileoutputstream.java:95) @ test.main(test.java:21)
conclusion : here iso-8859-1
encoding in run configuration scanner
not able read character console because console has different character encoding , have ??
filename
.
please change character encoding console, firmly believe using ide. may have changed or console inherited character encoding not suppose encode characters.
Comments
Post a Comment