Java中文件的隨機讀寫
Java.io 包提供了 RandomAccessFile 類用于隨機文件的創(chuàng)建和訪問。使用這個類,可以跳轉到文件的任意位置讀寫數(shù)據(jù)。程序可以在隨機文件中插入數(shù)據(jù),而不會破壞該文件的其他數(shù)據(jù)。此外,程序也可以更新或刪除先前存儲的數(shù)據(jù),而不用重寫整個文件。
RandomAccessFile類是Object類的直接子類,包含兩個主要的構造方法用來創(chuàng) 建RandomAccessFile 的對象,如表所示。
需要注意的是,mode 表示所創(chuàng)建的隨機讀寫文件的操作狀態(tài),其取值包括:
r:表示以只讀方式打開文件。
rw:表示以讀寫方式打開文件,使用該模式只用一個對象即可同時實現(xiàn)讀寫操作。
下表列出了 RandowAccessFile 類常用的方法及說明。
【例】模仿系統(tǒng)日志,將數(shù)據(jù)寫入到文件尾部。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
import java.io.*; class ep10_12{ public static void main(String args[]) throws IOException{ try { BufferedReader in= new BufferedReader( new InputStreamReader(System.in)); String s=in.readLine(); RandomAccessFile myFile= new RandomAccessFile( "ep10_12.log" , "rw" ); myFile.seek(myFile.length()); //移動到文件結尾 myFile.writeBytes(s+ "\n" ); //寫入數(shù)據(jù) myFile.close(); } catch (IOException e){} } } |
程序運行后在目錄中建立一個 ep10_12.log 的文件,每次運行時輸入的內(nèi)容都會在該文件內(nèi)容的結尾處添加。
Java中文件的壓縮處理
Java.util.zip 包中提供了可對文件的壓縮和解壓縮進行處理的類,它們繼承自字節(jié)流類OutputSteam 和 InputStream。其中 GZIPOutputStream 和 ZipOutputStream 可分別把數(shù)據(jù)壓縮成 GZIP 和 Zip 格式,GZIPInpputStream 和 ZipInputStream 又可將壓縮的數(shù)據(jù)進行還原。
將文件寫入壓縮文件的一般步驟如下:
生成和所要生成的壓縮文件相關聯(lián)的壓縮類對象。
壓縮文件通常不只包含一個文件,將每個要加入的文件稱為一個壓縮入口,使用ZipEntry(String FileName)生成壓縮入口對象。
使用 putNextEntry(ZipEntry entry)將壓縮入口加入壓縮文件。
將文件內(nèi)容寫入此壓縮文件。
使用 closeEntry()結束目前的壓縮入口,繼續(xù)下一個壓縮入口。
將文件從壓縮文件中讀出的一般步驟如下:
生成和所要讀入的壓縮文件相關聯(lián)的壓縮類對象。
利用 getNextEntry()得到下一個壓縮入口。
【例】輸入若干文件名,將所有文件壓縮為“ep10_13.zip”,再從壓縮文件中解壓并顯示。
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
|
import java.io.*; import java.util.*; import java.util.zip.*; class ep10_13{ public static void main(String args[]) throws IOException{ FileOutputStream a= new FileOutputStream( "ep10_13.zip" ); //處理壓縮文件 ZipOutputStream out= new ZipOutputStream( new BufferedOutputStream(a)); for ( int i= 0 ;i<args.length;i++){ //對命令行輸入的每個文件進行處理 System.out.println( "Writing file" +args[i]); BufferedInputStream in= new BufferedInputStream( new FileInputStream(args[i])); out.putNextEntry( new ZipEntry(args[i])); //設置 ZipEntry 對象 int b; while ((b=in.read())!=- 1 ) out.write(b); //從源文件讀出,往壓縮文件中寫入 in.close(); } out.close(); //解壓縮文件并顯示 System.out.println( "Reading file" ); FileInputStream d= new FileInputStream( "ep10_13.zip" ); ZipInputStream inout= new ZipInputStream( new BufferedInputStream(d)); ZipEntry z; while ((z=inout.getNextEntry())!= null ){ //獲得入口 System.out.println( "Reading file" +z.getName()); //顯示文件初始名 int x; while ((x=inout.read())!=- 1 ) System.out.write(x); System.out.println(); } inout.close(); } } |
運行后,在程序目錄建立一個 ep10_13.zip 的壓縮文件,使用解壓縮軟件(如 WinRAR等),可以將其打開。命令提示符下,程序運行結果如圖所示: