Java method to read the txt file
- 2020-05-26 08:20:19
- OfStack
java reads the contents of the txt file. It can be understood as follows:
First, get a file handle. File file = new File(); file is the file handle. The two men connected to the telephone network. Now you can start making phone calls. Read party a's information via this line: new FileInputStream(file) this information has been read into memory at present. Next, it shall be interpreted into something that can be understood by party b Since you're using FileInputStream(). Then the corresponding method needs to use InputStreamReader() to interpret the data just loaded into memory When the reading is done, output it. That, of course, translates into data that IO can recognize. Then you need to call the bytecode reading method BufferedReader(). Each row in the txt file is read using the readline() method of bufferedReader().
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;
/**
*
@author Code farmers jiang
*
H20121012.java
*
2012-10-12 In the afternoon 11:40:21
*/
public class H20121012
{
/**
*
Function: Java read txt Content of file
*
Steps: 1 : get the file handle first
*
2 : gets the file handle as input 1 The input stream needs to be read
*
3 : after reading the input stream, the generated byte stream needs to be read
*
4 : 1 line 1 Line output. readline() .
*
Note: exceptions should be considered
*
@param filePath
*/
public static void readTxtFile(String
filePath){
try {
String
encoding="GBK";
File
file=new File(filePath);
if(file.isFile()
&& file.exists()){ // Determine if 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(" The specified file could not be found ");
}
}
catch (Exception
e) {
System.out.println(" Error reading file contents ");
e.printStackTrace();
}
}
public static void main(String
argv[]){
String
filePath = "L:\\Apache\\htdocs\\res\\20121012.txt";
//
"res/";
readTxtFile(filePath);
}
}