我正在尝试从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();
}
}
答案 0 :(得分:3)
看着
new FileWriter("src/opinarium3/media/presentaciones/"+title+"/comments/...")
我看到你正在尝试从变量title引入一个目录。不确定这是否会创建所有缺少的目录。因此,请确保该目录存在并在写入以下两个级别的文件之前创建它。
答案 1 :(得分:2)
new FileWriter
永远不会创建目录。如果目录不存在,它将抛出FileNotFoundException
。
要创建目录(以及所有不存在的父目录),您可以使用以下内容:
new File("src/opinarium3/media/presentaciones/"+title+"/comments/").mkdirs();
答案 2 :(得分:1)
您可以根据文件位置尝试任何一个。只需使用前缀/
即可开始查看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());
注意:尽量避免路径中的空格。
首先检查文件夹(目录)是否存在:
示例代码:
File f = new File("/Path/To/File/or/Directory");
if (f.exists() && f.isDirectory()) {
...
}