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

标签 java

我有一个返回 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/

相关文章:

java - 如何在没有组件扫描xml的情况下在spring中配置 Controller ?

java PosixFileAttributes 返回错误的 atime 和 mtime

java - 在不加载 View 的情况下从 fragment 中获取数据

java - 用java开发图像编辑器

java - float 转换过程中可能会丢失精度

java - java类中用户定义的数组大小

java - Cassandra datastax一致性级别问题

java - Calendar.getInstance() 和 GregorianCalendar.getInstance() 之间的区别

java - 在 Java 中的 JButton 上绘画

java - 用于 JSON 的 jQuery