RandomAccessFile
RandomAccessFile
RandomAccessFile
是 Java 提供的用于读写文件的类,与普通的输入输出流不同的是,RandomAccessFile
具备随机访问文件的能力。
构造方法
RandomAccessFile
的构造方法有两个参数,分别是文件名和访问模式。访问模式有"r"(只读)、“rw”(读写)、“rws”(读写并同步文件内容)、“rwd”(读写并同步文件元数据)四种。通过指定访问模式,我们可以决定RandomAccessFile
对文件的读写权限。
1 |
|
常用方法
-
read
1
2
3public int read(byte[] b, int off, int len) throws IOException {
return readBytes(b, off, len);
} -
write
1
2
3public void write(byte[] b) throws IOException {
writeBytes(b, 0, b.length);
} -
seek
Sets the file-pointer offset, measured from the beginning of this file, at which the next read or write occurs. The offset may be set beyond the end of the file. Setting the offset beyond the end of the file does not change the file length. The file length will change only by writing after the offset has been set beyond the end of the file.
1
2
3
4
5
6
7public void seek(long pos) throws IOException {
if (pos < 0) {
throw new IOException("Negative seek offset");
} else {
seek0(pos);
}
} -
getFilePointer
Returns the current offset in this file
1
public native long getFilePointer() throws IOException;
案例一
从一个文件读入输出到另一个文件
-
常用的写法
-
字节流
1
2
3
4
5
6
7
8
9
10
11
12try (
FileInputStream fileInputStream = new FileInputStream("yy.txt");
BufferedInputStream bri = new BufferedInputStream(fileInputStream);
FileOutputStream fileOutputStream = new FileOutputStream("yk.txt");
BufferedOutputStream bro = new BufferedOutputStream(fileOutputStream);
) {
int len;
byte[] bytes = new byte[1024];
while ((len = bri.read(bytes)) != -1) {
bro.write(bytes, 0, len);
}
} -
字符流
1
2
3
4
5
6
7
8
9
10
11
12try(
FileReader fileReader = new FileReader("yy.txt");
FileWriter fileWriter = new FileWriter("yk.txt");
BufferedReader br = new BufferedReader(fileReader);
BufferedWriter bw = new BufferedWriter(fileWriter);
) {
char[] chars = new char[1024];
int len;
while ((len = br.read(chars)) != -1) {
bw.write(chars, 0, len);
}
}
-
-
RandomAccessFile
1
2
3
4
5
6
7
8
9
10try(
RandomAccessFile ri = new RandomAccessFile("yy.txt", "rw");
RandomAccessFile ro = new RandomAccessFile("yk.txt", "rw");
) {
byte[] bytes = new byte[1024];
int len;
while ((len = ri.read(bytes)) != -1) {
ro.write(bytes, 0, len);
}
}
案例二
多个线程给不同的位置写字节
1 |
|
RandomAccessFile
http://example.com/2023/11/06/RandomAccessFile/