java – 为什么FileWriter没有创建新文件? FileNotFoundException

参见英文答案 > Why FileWriter doesn’t create a new file?                                    1个
所以我有一个代码片段如下.我试图找出它抛出FileNotFoundException的原因.

File file= new File (WORKSPACE_PATH+fname);
FileWriter fw;
if (file.exists())
{
     fw = new FileWriter(file,true);//if file exists append to file. Works fine.
}
else
{
     fw = new FileWriter(file);// If file does not exist. Create it. This throws a FileNotFoundException. Why? 
}

解决方法:

在创建文件时使用连接将不会添加必要的路径分隔符.

File file = new File(WORKSPACE_PATH, fname);
上一篇:IO流(1)--文件流及其原理


下一篇:Java基础13-字符串缓冲流;字节流