gpt4 book ai didi

java - 文件写入失败,出现 java.io.FileNotFoundException :

转载 作者:行者123 更新时间:2023-12-01 17:51:39 31 4
gpt4 key购买 nike

我有一个返回 TreeMap 并尝试将该 TreeMap 中的内容写入文件的方法。在 Linux 中,我尝试在目录 /home/sid/AutoFile/ 中创建一个新文件,并将当前日期附加到文件名。

这是我想到的:

public void createReconFile() throws SQLException, IOException {
Map<String, String> fileInput = new TreeMap<String, String>();
fileInput = getDiffTableCount();
Set<String> countKeys = fileInput.keySet();
Iterator<String> fileInpIter = countKeys.iterator();
Writer output = null;
//creating a file with currentDate
DateFormat df = new SimpleDateFormat("MM/dd/yyyy:HH:mm:ss");
Date today = Calendar.getInstance().getTime();
String reportDate = df.format(today);
System.out.println(reportDate);
try {
File file = new File("/home/sid/AutoFile/" + "count" + reportDate);
output = new BufferedWriter(new FileWriter(file));
System.out.println("Created new file");
while(fileInpIter.hasNext()) {
String tableName = fileInpIter.next();
String cdp = fileInput.get(tableName);
output.write(tableName +" " + cdp+"\n");
}
} catch(IOException e) {
System.out.println("File Writing failed");
e.printStackTrace();
} catch(Exception e) {
e.printStackTrace();
} finally {
System.out.println("Closing the file...");
output.close();
}
}

但它以异常(exception)结束:

03/23/2018:05:35:30
File Writing failed
java.io.FileNotFoundException: /home/sid/AutoFile/count03/23/2018:05:35:30 (No such file or directory)
at java.io.FileOutputStream.open0(Native Method)
at java.io.FileOutputStream.open(FileOutputStream.java:270)
at java.io.FileOutputStream.<init>(FileOutputStream.java:213)
at java.io.FileOutputStream.<init>(FileOutputStream.java:162)

目录:/home/sid/AutoFile/count03/23/2018:05:35:30 已经存在,我试图在每次调用该方法时创建一个新文件。谁能告诉我我在这里犯了什么错误以及如何使用 java 正确创建文件。

最佳答案

Linux 中的文件名不能有正斜杠。所以我相信你想用作文件名的日期格式被linux视为目录。您需要更改日期格式,以便其中没有任何正斜杠,或者您可以使用以下行首先创建一个目录,然后在该目录中写入文件。

new File("/home/ist/"+ "count03/23").mkdirs();

此外,如果您已经有一个目录/home/sid/AutoFile/count03/23/2018:05:35:30 那么您不能在 linux 中的同一位置拥有相同名称的文件。

关于java - 文件写入失败,出现 java.io.FileNotFoundException :,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49443322/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com