我們先來(lái)看個(gè)例子
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
|
import java.io.*; /** * Created by liguoqing on 2016/3/28. */ public class ReadTxtFile { public static void readTxt(String filePath) { try { File file = new File(filePath); if (file.isFile() && file.exists()) { InputStreamReader isr = new InputStreamReader( new FileInputStream(file), "utf-8" ); BufferedReader br = new BufferedReader(isr); String lineTxt = null ; while ((lineTxt = br.readLine()) != null ) { System.out.println(lineTxt); } br.close(); } else { System.out.println( "文件不存在!" ); } } catch (Exception e) { System.out.println( "文件讀取錯(cuò)誤!" ); } } public static void main(String[] args) { String filePath = "D:\\test\\我.txt" ; readTxt(filePath); } } |
看完上面的例子,我們?cè)賮?lái)詳細(xì)研究下
java讀取txt文件內(nèi)容。可以作如下理解:
首先獲得一個(gè)文件句柄。File file = new File(); file即為文件句柄。兩人之間連通電話網(wǎng)絡(luò)了。接下來(lái)可以開(kāi)始打電話了。
通過(guò)這條線路讀取甲方的信息:new FileInputStream(file) 目前這個(gè)信息已經(jīng)讀進(jìn)來(lái)內(nèi)存當(dāng)中了。接下來(lái)需要解讀成乙方可以理解的東西
既然你使用了FileInputStream()。那么對(duì)應(yīng)的需要使用InputStreamReader()這個(gè)方法進(jìn)行解讀剛才裝進(jìn)來(lái)內(nèi)存當(dāng)中的數(shù)據(jù)
解讀完成后要輸出呀。那當(dāng)然要轉(zhuǎn)換成IO可以識(shí)別的數(shù)據(jù)呀。那就需要調(diào)用字節(jié)碼讀取的方法BufferedReader()。同時(shí)使用bufferedReader()的readline()方法讀取txt文件中的每一行數(shù)據(jù)哈。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
|
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 碼農(nóng)小江 * H20121012.java * 2012-10-12下午11:40:21 */ public class H20121012 { /** * 功能:Java讀取txt文件的內(nèi)容 * 步驟:1:先獲得文件句柄 * 2:獲得文件句柄當(dāng)做是輸入一個(gè)字節(jié)碼流,需要對(duì)這個(gè)輸入流進(jìn)行讀取 * 3:讀取到輸入流后,需要讀取生成字節(jié)流 * 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( "讀取文件內(nèi)容出錯(cuò)" ); e.printStackTrace(); } } public static void main(String argv[]){ String filePath = "L:\\Apache\\htdocs\\res\\20121012.txt" ; // "res/"; readTxtFile(filePath); } } |