使用 Java FileWriter 的文件未找到异常

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24969522/
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-14 16:04:05  来源:igfitidea点击:

File Not Found Exception using Java FileWriter

javafile-iofilewriterbufferedwriter

提问by Alexis R Devitre

I am trying to write to a txt file from a JAVA Application. I have tried using Buffered Writer, then just FileWriter to create a new file within a potentially new (not indefinitely since more files with different names will be later programatically written there by the same method) subfolder. I get the following error message (It's actually much longer but I think this is the key part of it):

我正在尝试从 JAVA 应用程序写入 txt 文件。我曾尝试使用 Buffered Writer,然后仅使用 FileWriter 在一个潜在的新(不是无限期的,因为以后将通过相同的方法以编程方式写入更多具有不同名称的文件)子文件夹中创建一个新文件。我收到以下错误消息(实际上更长,但我认为这是其中的关键部分):

java.io.FileNotFoundException: src/opinarium3/media/presentaciones/Los fantasmas del Sistema Solar/comments/2014-07-26.txt (No such file or directory) at java.io.FileOutputStream.open(Native Method)

java.io.FileNotFoundException: src/opinarium3/media/presentaciones/Los fantasmas del Sistema Solar/comments/2014-07-26.txt(没有这样的文件或目录)在 java.io.FileOutputStream.open(本地方法)

And this is the code firing the issue (it activates as you press a button to register a comment having been filled in a custom form):

这是引发问题的代码(它会在您按下按钮注册已在自定义表单中填写的评论时激活):

private void fileCommentOnPresentation(String title, String positiveComments, String negativeComments, int grade) throws IOException{
    FileWriter bw;
    try{
        bw = new FileWriter("src/opinarium3/media/presentaciones/"+title+"/comments/"+Date.valueOf(LocalDate.now())+".txt");
        bw.write(title+"\n"+positiveComments+"\n"+negativeComments+"\n"+grade);
        bw.flush();
        bw.close();
    }catch(IOException e){
        e.printStackTrace();
    }
}

回答by Braj

You can try any one based on file location. Just use prefix /to start looking into srcfolder.

您可以根据文件位置尝试任何一种。只需使用前缀/开始查看src文件夹。

// Read from resources folder parallel to src in your project
File file1 = new File("resources/abc.txt");
System.out.println(file1.getAbsolutePath());

// Read from src/resources folder
File file2 = new File(getClass().getResource("/resources/abc.txt").toURI());
System.out.println(file2.getAbsolutePath());

Note:Try to avoid spaces in the path.

注意:尽量避免路径中出现空格。

First check whether folder(directory) exists or not:

首先检查文件夹(目录)是否存在:

sample code:

示例代码:

File f = new File("/Path/To/File/or/Directory");
if (f.exists() && f.isDirectory()) {
   ...
}

Read more...

阅读更多...

回答by laune

Looking at

看着

new FileWriter("src/opinarium3/media/presentaciones/"+title+"/comments/...")

I see that you are trying to introduce a directory from variable title. Not sure whether this creates all missing directories. So please make sure that this directory exists and create it before writing to the file two levels below.

我看到您正试图从变量标题中引入一个目录。不确定这是否会创建所有丢失的目录。所以在写入下面两级文件之前,请确保该目录存在并创建它。

回答by user253751

new FileWriterwill never create a directory. It will throw a FileNotFoundExceptionif the directory doesn't exist.

new FileWriter永远不会创建目录。FileNotFoundException如果目录不存在,它将抛出一个。

To create the directory (and all parent directories that don't already exist), you can use something like this:

要创建目录(以及所有尚不存在的父目录),您可以使用以下内容:

new File("src/opinarium3/media/presentaciones/"+title+"/comments/").mkdirs();