本文實例講述了Java讀取文件的簡單實現方法,非常實用。分享給大家供大家參考之用。具體方法如下:
這是一個簡單的讀取文件的代碼,并試著讀取一個log文件,再輸出。
主要代碼如下:
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
|
import java.io.*; public class FileToString { public static String readFile(String fileName) { String output = "" ; File file = new File(fileName); if (file.exists()){ if (file.isFile()){ try { BufferedReader input = new BufferedReader ( new FileReader(file)); StringBuffer buffer = new StringBuffer(); String text; while ((text = input.readLine()) != null ) buffer.append(text + "/n" ); output = buffer.toString(); } catch (IOException ioException){ System.err.println( "File Error!" ); } } else if (file.isDirectory()){ String[] dir = file.list(); output += "Directory contents:/n" ; for ( int i= 0 ; i<dir.length; i++){ output += dir[i] + "/n" ; } } } else { System.err.println( "Does not exist!" ); } return output; } public static void main (String args[]){ String str = readFile( "C:/1.txt" ); System.out.print(str); } } |
輸出結果如下:
奧運加油!
北京加油!
中國加油!
這里FileReader類打開一個文件,但是它并不知道如何讀取一個文件,這就需要BufferedReader類提供讀取文本行的功能。這就要聯合這兩個類的功能,來實現打開文件并讀取文件的目的。這是一種包裝流對象的技術,即將一個流的服務添加到另一個流中。
另外需要指出的是,Java在按照路徑打開文件時,"/"和"/"都是認可的,只是在用到"/"時,要用另一個"/"轉義一下。
希望本文所述對大家Java程序設計的學習有所幫助。