Transferred from: http://www.cnblogs.com/manongxiaojiang/archive/2012/10/13/2722068.html
Java reads the contents of the TXT file. Can be understood as follows:
First, get a file handle. File File = new file (); File is a handle to the document. There was a network of calls between the two of them. Then you can start making a phone call.
This line reads the information of party A: new FileInputStream (file) is now read in memory. Then it needs to be interpreted as something that B can understand.
Since you have used FileInputStream (). Then the corresponding need to use InputStreamReader () This method to interpret the memory just loaded in the data
After the interpretation is finished to output AH. Of course it's going to be converted into data that the IO can recognize. Then you need to call the byte code read Method BufferedReader (). Use the ReadLine () method of BufferedReader () to read each row of data in the TXT file.
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 码农小江
* H20121012.java
* 2012-10-12下午11:40:21
*/
public
class
H20121012 {
/**
* 功能:Java读取txt文件的内容
* 步骤:1:先获得文件句柄
* 2:获得文件句柄当做是输入一个字节码流,需要对这个输入流进行读取
* 3:读取到输入流后,需要读取生成字节流
* 4:一行一行的输出。readline()。
* 备注:需要考虑的是异常情况
* @param filePath
*/
public
static
void
readTxtFile(String filePath){
try
{
String encoding=
"GBK"
;
File file=
new
File(filePath);
if
(file.isFile() && file.exists()){
//判断文件是否存在
InputStreamReader read =
new
InputStreamReader(
new
FileInputStream(file),encoding);
//考虑到编码格式
BufferedReader bufferedReader =
new
BufferedReader(read);
String lineTxt =
null
;
while
((lineTxt = bufferedReader.readLine()) !=
null
){
System.out.println(lineTxt);
}
read.close();
}
else
{
System.out.println(
"找不到指定的文件"
);
}
}
catch
(Exception e) {
System.out.println(
"读取文件内容出错"
);
e.printStackTrace();
}
}
public
static
void
main(String argv[]){
String filePath =
"L:\\Apache\\htdocs\\res\\20121012.txt"
;
// "res/";
readTxtFile(filePath);
}
}
Java method for reading txt files (go)