It can be understood as follows:
First get a file handle. File file = new File(); file is the file handle. The two of them have a telephone network connection. You can start calling next
Read Party A's information through this line: new FileInputStream(file) Currently, this information has been read into memory. Next, it needs to be interpreted as something that Party B can understand
Since you have used FileInputStream(). Then the corresponding method needs to be used to interpret the data loaded in the memory just now.
After the interpretation is completed, you need to output it. Of course, it needs to be converted into data that IO can recognize. Then you need to call the BufferedReader() method that reads bytecode. At the same time, use the readline() method of bufferedReader() to read each line of data in the txt file.
The code copy is as follows:
package com.campu;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.Reader;
public class H20121012 {
/**
* Function: Java reads the contents of txt files
* Step: 1: Get the file handle first
* 2: Obtaining the file handle is used to input a bytecode stream, and this input stream needs to be read.
* 3: After reading the input stream, you need to read the generated byte stream
* 4: Output of line by line. readline().
* Note: What needs to be considered is exceptional situations
* @param filePath
*/
public static void readTxtFile(String filePath){
try {
String encoding="GBK";
File file=new File(filePath);
if(file.isFile() && file.exists()){ //Judge whether the file exists
InputStreamReader read = new InputStreamReader(
new FileInputStream(file), encoding);// Consider the encoding format
BufferedReader bufferedReader = new BufferedReader(read);
String lineTxt = null;
while((lineTxt = bufferedReader.readLine()) != null){
System.out.println(lineTxt);
}
read.close();
}else{
System.out.println("Specified file not found");
}
} catch (Exception e) {
System.out.println("Error reading file content");
e.printStackTrace();
}
}
public static void main(String argv[]){
String filePath = "L://Apache//htdocs//res//20121012.txt";
// "res/";
readTxtFile(filePath);
}
}