標籤:
轉自:http://www.cnblogs.com/manongxiaojiang/archive/2012/10/13/2722068.html
java讀取txt檔案內容。可以作如下理解:
首先獲得一個檔案控制代碼。File file = new File(); file即為檔案控制代碼。兩人之間連通電話網路了。接下來可以開始打電話了。
通過這條線路讀取甲方的資訊:new FileInputStream(file) 目前這個資訊已經讀進來記憶體當中了。接下來需要解讀成乙方可以理解的東西
既然你使用了FileInputStream()。那麼對應的需要使用InputStreamReader()這個方法進行解讀剛才裝進來記憶體當中的資料
解讀完成後要輸出呀。那當然要轉換成IO可以識別的資料呀。那就需要調用位元組碼讀取的方法BufferedReader()。同時使用bufferedReader()的readline()方法讀取txt檔案中的每一行資料哈。
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讀取TXT檔案的方法 (轉)