IO File Operations in java: Reading Output by Line

Time:2019-10-10

IO File Operation in JavaIt is a very important part of java. In the written examination of financial securities companies, it often encounters the operation of files. Today’s article is about simple text files read by line and output to the console.


package com.lsl.readAndwrite;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

public class ReadAndOut {
    
    public static void main(String[] args) throws IOException {
        /*
         * 1. Open a file
         * 2. New an InputStream Reader_FileInputStream_file
         * 3. Read with BufferedReader (InputStreamReader) readLine () method
         * */
        File f = new File("D:\book\1.txt");
        InputStreamReader readf = new InputStreamReader(new FileInputStream(f),"GBK");
       // There is a possibility of scrambling
        BufferedReader bfReader = new BufferedReader(readf);
        String txtline = null;
        while ((txtline = bfReader.readLine()) != null) {
          System.out.println(txtline);
        }
        bfReader.close();
      };
}

Results Screenshot:
IO File Operations in java: Reading Output by Line

Scrambling problem:

FileReader gets characters, so bytes must have been recognized as characters by some kind of encoding.
The encoding method used by FileReader is the return value of Charset. defaultCharset (), and if it is a Chinese operating system, it is GBK.
FileReader can't set the encoding mode manually. In order to use other encoding methods, InputStreamReader can only be used instead.
Read with InputStreamReader

Recommended Today

Rethinking the Java static keyword

The Java class, while also wrote a lot of Java code, but there has been a lot of doubt, the static keyword has puzzled me for a long time, today didn’t mean to study, on zhihu check again carefully and found the best answer to the topic of https://www.zhihu.com/question/36615154 This article thoroughly understanding of the […]