随机存取文件流的使用
package com.random;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import org.junit.Test;
// 随机存取文件流的使用
public class RandomAccessFileTest {
// 在指定位置添加内容,原位置后的内容顺移
@Test
public void test03() throws IOException {
// 创建随机访问流
File file = new File("access.txt");
RandomAccessFile raf = new RandomAccessFile(file, "rw");
// 读取一行数据
String line = raf.readLine();
// 从读取到的数据中查找第一个字母o出现的位置
int index = line.indexOf("o");
// 设置读写内容的位置
raf.seek(index+1);
byte[] buf = new byte[5];
int len;
// 存储指定位置后的内容
String str = "";
while((len = raf.read(buf)) != -1) {
str += new String(buf, 0, len);
}
// 再次定义指针
raf.seek(index+1);
raf.write("java".getBytes());
raf.write(str.getBytes());
raf.close();
}
// 以追加的方式写出文件
@Test
public void test02() throws IOException {
File file = new File("access.txt");
long pos = file.length();
RandomAccessFile raf = new RandomAccessFile(file, "rw");
raf.seek(pos);
raf.write("java".getBytes());
raf.close();
}
// 写出文件
@Test
public void test01() throws IOException {
RandomAccessFile raf = new RandomAccessFile(
new File("access.txt"), "rw");
raf.write("hello".getBytes());
//raf.seek(2);
//raf.write("xx".getBytes());
raf.close();
}
}