Java中IO流 RandomAccessFile類實例詳解
RandomAccessFile
- java提供的對文件內容的訪問,既可以讀文件,也可以寫文件。
- 支持隨機訪問文件,可以訪問文件的任意位置。
- java文件模型,在硬盤上的文件是byte byte byte存儲的,是數據的集合
- 打開文件,有兩種模式,“rw”讀寫、“r”只讀;RandomAccessFile raf = new RandomAccessFile(file, "rw");,文件指針,打開文件時指針在開頭 point = 0;
- 寫方法, raf.write()-->只寫一個字節(后八位),同時指針指向下一個位置,準備再次寫入
- 讀方法,int b = raf.read()-->讀一個字節
- 文件讀寫完成以后一定要關閉(Oracle官方說明)
RafDemo.java
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
|
package com.test.io; import java.io.File; import java.io.IOException; import java.io.RandomAccessFile; import java.util.Arrays; public class RafDemo { public static void main(String[] args) throws IOException { File demo = new File( "demo" ); if (!demo.exists()) { demo.mkdir(); } File file = new File(demo, "raf.dat" ); if (!file.exists()) { file.createNewFile(); } RandomAccessFile raf = new RandomAccessFile(file, "rw" ); System.out.println(raf.getFilePointer()); raf.write( 'A' ); //一個char型占兩個字節,但是write一次只寫入一個字節(A字符的后八位) System.out.println(raf.getFilePointer()); raf.write( 'B' ); int i = 0x7fffffff ; raf.write(i >>> 24 ); //寫入i的高八位 raf.write(i >>> 16 ); raf.write(i >> 8 ); raf.write(i); System.out.println(raf.getFilePointer()); //直接寫入一個int raf.writeInt(i); String s = "你" ; byte [] b = s.getBytes( "utf8" ); raf.write(b); System.out.println(raf.length()); //讀文件,必須把指針移到頭部 raf.seek( 0 ); //一次性讀取,把文件中的內容都讀到字節數組中 byte [] buf = new byte [( int ) raf.length()]; raf.read(buf); System.out.println(Arrays.toString(buf)); for ( byte c : buf) { System.out.print(Integer.toHexString(c & 0xff ) + " " ); } //關閉文件 raf.close(); } } |
執行結果:
1
2
3
4
5
6
|
0 1 6 13 [ 65 , 66 , 127 , - 1 , - 1 , - 1 , 127 , - 1 , - 1 , - 1 , - 28 , - 67 , - 96 ] 41 42 7f ff ff ff 7f ff ff ff e4 bd a0 |
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
原文鏈接:http://www.cnblogs.com/tianxintian22/p/6820691.html