Java BufferWriter Write File Can't Write in or Missing Data Solution

  • 2021-11-02 00:44:55
  • OfStack

Java BufferWriter The file is empty or the data is incomplete after writing the file

In the process of programming, reading and writing files is a very common operation. Here, I ask to introduce the situation that I encountered recently when I couldn't write a centralized file. First, give the complete code.


import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
public class Main {
 public static void main(String[] args) throws IOException {
  String filename = "src/data/write.txt";
  BufferedWriter bw = new BufferedWriter(new FileWriter(filename));
  for (int i = 1; i <= 10; i++) {
   bw.write(i + " ");
  }
  bw.close();
 }
}

This code is the implementation of the normal file writing process. First, define the BufferedWriter object to point to the corresponding file, then perform the write operation, and close bw. close () after completion;

Problem 1: Forget bw. close () during encoding, and the data will be written incompletely or empty

This is a very common error, because BufferedWriter is written in a buffer way, that is, the written data is put into the buffer first, and then written to the file after the buffer is full. The purpose of close () is to force the data in the buffer to be written to the file, even if the data in the buffer is not satisfied.

Problem 2: That is, the format of the written file may cause the file to be empty

What I have encountered here is, It is planned to write thousands of data into txt text and place them in 1 line, separated by spaces, and an empty file will appear. This is because thousands of data cannot be placed in 1 line, because txt and other file formats have no requirement on the number of lines of the file, but have a requirement on the number of columns, that is, the data in 1 line cannot exceed the maximum value, but enough lines can be written.

Here is an example to illustrate the situation:


import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
public class Main {
 public static void main(String[] args) throws IOException {
  String filename = "src/data/write.txt";
  BufferedWriter bw = new BufferedWriter(new FileWriter(filename));
  for (int i = 1; i <= 3000; i++) {
   bw.write(i + " ");
  }
  bw.close();
 }
}

It's the same code as before, but you need 3000 pieces of data and write them on the same line, and you will find an empty file.

And bw. write (i + ""); Replace it with bw. write (i + "\ n"); You will find that the file was successfully written.

BufferedWriter Writing File Considerations

For text files, it is more efficient to read and write with BufferedReader and BufferedWriter, because of the use of cache area. Its workflow is: first read and write the text content to the cache area, and when the cache area is full, automatically read and write the contents in the cache area to the file.

Question:

If the buffer is just full at the same time as reading and writing, Then the buffer will automatically read or write the data inside to the target file. In this case, it will not be a problem for you to call close () method directly to close the stream. However, if the buffer is not full when the file is read and written, you will call close () method directly. At this time, the data loaded in the buffer will not automatically read or write to the target file, resulting in the loss of this part of the data in the buffer.

Solution:

Invoke the flush () method before close () to manually read and write buffer data to the target file

eg:


@Test
public void test5(){
    BufferedWriter bufferedWriter = null;
    BufferedReader bufferedReader = null;
    try {
        bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream("G://reader.txt"),"GBK"));
        // Write stream , Set the cache size to 1024K
        bufferedWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("G://writer.txt"),"UTF-8"),1024);
        String line;
        while ((line = bufferedReader.readLine()) != null) {
            bufferedWriter.write(line);
            bufferedWriter.newLine();
        }
    }catch (Exception e){
        log.error(" Anomaly :{}",e);
    }finally {
        if (bufferedWriter != null) {
            try {
                // Refresh the cache 
                bufferedWriter.flush();
                bufferedWriter.close();
            } catch (IOException e) {
                log.error(" Close output stream exception :{}", e);
            }
        }
        if (bufferedReader != null) {
            try {
                bufferedReader.close();
            } catch (IOException e) {
                log.error(" Close read stream exception :{}", e);
            }
        }
    }
    log.info(" End safely ");
}

Related articles: