一.在 JDK 1.0 中,通常是用 InputStream & OutputStream 這兩個(gè)基類來(lái)進(jìn)行讀寫操作的。
InputStream 中的 FileInputStream 類似一個(gè)文件句柄,通過(guò)它來(lái)對(duì)文件進(jìn)行操作,類似的,在
OutputStream 中我們有 FileOutputStream 這個(gè)對(duì)象。
用FileInputStream 來(lái)讀取數(shù)據(jù)的常用方法是:
FileInputStream fstream = new FileInputStream(args[0]);
DataInputStream in = new DataInputStream(fstream);
用 in.readLine() 來(lái)得到數(shù)據(jù),然后用 in.close() 關(guān)閉輸入流。
完整代碼見(jiàn) Example 1。
用FileOutputStream 來(lái)寫入數(shù)據(jù)的常用方法是:
FileOutputStream out out = new FileOutputStream("myfile.txt");
PrintStream p = new PrintStream( out );
用 p.println() 來(lái)寫入數(shù)據(jù),然后用 p.close() 關(guān)閉輸入。
完整代碼見(jiàn) Example 2。
二.在 JDK 1.1中,支持兩個(gè)新的對(duì)象 Reader & Writer, 它們只能用來(lái)對(duì)文本文件進(jìn)行操作,而
JDK1.1中的 InputStream & OutputStream 可以對(duì)文本文件或二進(jìn)制文件進(jìn)行操作。
用FileReader 來(lái)讀取文件的常用方法是:
FileReader fr = new FileReader("mydata.txt");
BufferedReader br = new BufferedReader(fr);
用 br.readLing() 來(lái)讀出數(shù)據(jù),然后用br.close() 關(guān)閉緩存,用fr.close() 關(guān)閉文件。
完整代碼見(jiàn) Example 3。
用 FileWriter 來(lái)寫入文件的常用方法是:
FileWriter fw = new FileWriter("mydata.txt");
PrintWriter out = new PrintWriter(fw);
在用out.print 或 out.println 來(lái)往文件中寫入數(shù)據(jù),out.print 和 out.println的唯一區(qū)別是后者寫
入數(shù)據(jù)或會(huì)自動(dòng)開(kāi)一新行。寫完后要記得 用out.close() 關(guān)閉輸出,用fw.close() 關(guān)閉文件。
完整代碼見(jiàn) Example 4。
-------------------------------------------------------------- following is the source code of examples------------------------------------------------------









































Example 2:































Example 3:











































Example 4:


































