A mistake made with BufferedReader

 

Use BufferedReader to read file data. Since the data is generated and exported by the device according to the format, it needs to be read by line, divided, and then valued.

 

Here, when I read the file, I judge whether the byte read by bufferedReader.read() is -1 in the while condition. As a result, the first byte (character) of each line is lost during reading. now:

// Pass in the fileAddress file path
BufferedReader br = new BufferedReader(new FileReader(new File(fileAddress)));
int len;// used to record the bytes read, the range is 0 - 65535
while ((len = br.read()) != -1) {
    String line = br.readLine();
    // Process by regular segmentation
    ...
    // release resources
    br.close();
}

 Since the read() method has already fetched the read bytes, the first byte is always missing when using the readLine() method.

Should be handled as follows:

BufferedReader br = new BufferedReader(new FileReader(new File(fileAddress)));
String line = null;
while ((line = br.readLine()) != null) {
    // Direct string processing on line
    ...
    // release resources
    br.close();
}

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326177750&siteId=291194637