Java 为什么 FileWriter 不创建新文件?文件未找到异常

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25291770/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 00:03:16  来源:igfitidea点击:

Why is FileWriter not creating a new file ? FileNotFoundException

javafile-iofilewriter

提问by seeker

So I have a code snippet as follows. Im trying to find out why it throws a FileNotFoundException.

所以我有一个代码片段如下。我试图找出它抛出 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? 
}

回答by nbz

Using concatenation when creating the File won't add the necessary path separator.

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

File file = new File(WORKSPACE_PATH, fname);

回答by roelofs

This might work:

这可能有效:

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
{
   file.createNewFile();
   fw = new FileWriter(file);
}

回答by roelofs

You need to add a separator (Windows : \and Unix : /, you can use File.separatorto get the system's separator) if WORKSPACE_PATHdoes not have one at its end, and manually creating the file with its parent directories might help.

如果末尾没有分隔符,则需要添加分隔符(Windows :\和 Unix : /,您可以使用它File.separator来获取系统的分隔符)WORKSPACE_PATH,并且使用其父目录手动创建文件可能会有所帮助。

Try this if WORKSPACE_PATHdoes not have a separator at its end :

如果WORKSPACE_PATH末尾没有分隔符,请尝试此操作:

File file = new File(WORKSPACE_PATH + File.separator + fname);

And add this before fw = new FileWriter(file);

并在此之前添加 fw = new FileWriter(file);

file.mkdirs(); // If the directory containing the file and/or its parent(s) does not exist
file.createNewFile();