FileWriter not writing?

后端 未结 1 939
遥遥无期
遥遥无期 2021-01-29 10:41

I have this snippet of code:

        try {
            f1 = new File(\"sink.txt\");
            f1.createNewFile();
            fw = new FileWriter(f1);
                 


        
相关标签:
1条回答
  • 2021-01-29 11:21

    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.

    0 讨论(0)
提交回复
热议问题