FileWriter不写?

时间:2016-04-16 02:40:19

标签: java file filewriter

我有这段代码:

        try {
            f1 = new File("sink.txt");
            f1.createNewFile();
            fw = new FileWriter(f1);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        ... code ...
        System.out.println(sequence);
        System.out.println(mySink.indexOf(sequence));
        String result = "";
        int firstIndex = mySink.indexOf(sequence);
        if (firstIndex >= 0) {
            System.out.println(true);
            int secondIndex = mySink.indexOf(sequence, firstIndex + sequence.length());
            if (secondIndex >= 0) {
                System.out.println(true);
                result = mySink.substring(firstIndex, secondIndex + sequence.length());
                System.out.println(result);
            }
        }
        try { // Write it to file
            fw.write(result);
        } catch (IOException e) {
            e.printStackTrace();
        } 
        System.out.println("done");

当我跑步时,它会在sequence内打印字符串mySink及其索引。然后它进入if语句并打印出两个true并打印出result所以我知道result已成功初始化。但是当我查看文件sink.txt时,我发现它是空白的。为什么这样做?我在代码中遗漏了什么吗?它之前工作,我添加了一些代码,它做到了这一点。在执行程序期间,我从未触及FileWriterFile。提前致谢!

如果你想看到,这是我的输出:

[93, 73, 74, 81, 89, 70, 50, 80, 51, 83, 62, 13, 50, 0, 40, 98, 48, 43, 47, 89]
2000466
true
true
[93, 73, 74, 81, 89, 70, 50, 80, 51, 83, 62, 13, 50, 0, 40, 98, 48, 43, 47, 89]
[93, 73, 74, 81, 89, 70, 50, 80, 51, 83, 62, 13, 50, 0, 40, 59, 48, 43, 47, 89]
[93, 73, 74, 81, 89, 70, 50, 80, 51, 83, 62, 13, 50, 0, 81, 59, 48, 43, 47, 89]
[93, 73, 74, 81, 89, 70, 50, 80, 51, 83, 62, 13, 50, 0, 81, 98, 48, 43, 47, 89]
[93, 73, 74, 81, 89, 70, 50, 80, 51, 83, 62, 13, 50, 0, 40, 98, 48, 43, 47, 89]
done

1 个答案:

答案 0 :(得分:1)

简短的回答是,您没有关闭(或刷新)FileWriter。这意味着您的应用程序将退出,并且未写入的数据仍然位于文件缓冲区中。

您的代码中还有许多其他错误。从顶部开始:

    try {
        f1 = new File("sink.txt");
        f1.createNewFile();
        fw = new FileWriter(f1);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
  1. createNewFile电话是多余的。以下new FileWriter将创建文件。

  2. 您正在捕捉异常并继续,好像什么都没发生过一样。你>>不能<<继续这些例外。如果您成功打开文件,其余代码只能正常工作。

  3. 除非您打算以不同方式处理它,否则不需要捕获FileNotFoundException。捕获IOException就足够了,因为它是前者的超类。

  4. 此时,您应该使用try-with-resources:

    f1 = new File("sink.txt");
    try (FileWriter fw = new FileWriter(f1)) {
    
       // compute stuff
    
       // write stuff to file
    
    } catch (FileNotFoundException ex) {
        System.out.println(ex.getMessage());
    } catch (IOException ex) {
        // This is ugly for a real app.  However, an IOException that
        // is not a FileNotFoundException is "unexpected" at this point
        // and providing a user-friendly explanation would be tricky. 
        ex.printStackTrace();  
    }
    

    try-with-resources将导致fw在块退出时自动关闭。关闭作者将首先冲洗它。