File Not Found Exception using Java FileWriter
我正在尝试从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)
这是引发该问题的代码(当您按下按钮以注册以自定义形式填写的评论时,它将激活):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | 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+"\ "+positiveComments+"\ "+negativeComments+"\ "+grade); bw.flush(); bw.close(); }catch(IOException e){ e.printStackTrace(); } } |
要创建目录(以及所有尚不存在的父目录),可以使用以下命令:
1 |
看着
1 |
我看到您正在尝试从变量title引入目录。不确定是否会创建所有丢失的目录。因此,在写入下面两个级别的文件之前,请确保该目录存在并创建它。
您可以根据文件位置尝试任何一种。只需使用前缀
1 2 3 4 5 6 7 | // 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()); |
注意:尝试避免路径中出现空格。
首先检查文件夹(目录)是否存在:
示例代码:
了解更多...