Ale*_*tre 4 java file-io filewriter bufferedwriter
我正在尝试从 JAVA 应用程序写入 txt 文件。我尝试过使用 Buffered Writer,然后仅使用 FileWriter 在一个可能新的子文件夹中创建一个新文件(不是无限期的,因为稍后将通过相同的方法以编程方式写入更多具有不同名称的文件)。我收到以下错误消息(实际上更长,但我认为这是它的关键部分):
java.io.FileNotFoundException:src/opinarium3/media/presentaciones/Los fantasmas del Sistema Solar/comments/2014-07-26.txt(没有这样的文件或目录)在java.io.FileOutputStream.open(本机方法)
这是引发问题的代码(当您按下按钮注册已填写自定义表单的评论时,它会激活):
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();
}
}
Run Code Online (Sandbox Code Playgroud)
new FileWriter永远不会创建目录。FileNotFoundException如果目录不存在,它将抛出 a 。
要创建目录(以及所有尚不存在的父目录),您可以使用如下内容:
new File("src/opinarium3/media/presentaciones/"+title+"/comments/").mkdirs();
Run Code Online (Sandbox Code Playgroud)