java写入文件中文_java – 无法将中文字符写入文件名

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)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值