FileWriter not writing?

有些话、适合烂在心里 提交于 2019-12-02 14:23:18

The short answer is that you are not closing (or flushing) your FileWriter. That means that you application will exit with unwritten data still sitting in the file buffers.

There are a number of other mistakes in your code. Starting from the top:

    try {
        f1 = new File("sink.txt");
        f1.createNewFile();
        fw = new FileWriter(f1);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
  1. The createNewFile call is redundant. The following new FileWriter will create the file.

  2. You are catching exceptions and continuing as if nothing has happened. You >>cannot<< continue from those exceptions. The rest of your code can only work properly if you succeeded in opening the file.

  3. You don't need to catch FileNotFoundException unless you intend to handle it differently. Catching IOException is sufficient, because it is a superclass of the former.

  4. At this point, you should be using 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();  
    }
    

    The try-with-resources will cause fw to be closed automatically when the block exits. Closing the writer will first flush it.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!