Use Java program to read file information line by line

When reading the content of a file, reading line by line is convenient for us to manipulate the content.

For example, for fixed format content, the first column of each row has the information we need to cut out. At this time, you need to read line by line.

There are two ways to read the contents of a file line by line using the Java language:

  1. FileInputStream and BufferedReader
private static void readFile1(File fin) throws IOException {
    
    
	FileInputStream fis = new FileInputStream(fin);
 
	BufferedReader br = new BufferedReader(new InputStreamReader(fis));
 
	String line = null;
	while ((line = br.readLine()) != null) {
    
    
		System.out.println(line);
	}
 
	br.close();
        fis.close();
}

  1. FileReader and BufferedReader
private static void readFile2(File fin) throws IOException {
    
    
	
	BufferedReader br = new BufferedReader(new FileReader(fin));
 
	String line = null;
	while ((line = br.readLine()) != null) {
    
    
		System.out.println(line);
	}
 
	br.close();
}

After reading each row of data, you can perform the operations you want.

Guess you like

Origin blog.csdn.net/DreamsArchitects/article/details/108835203