/**
* 将文件中的最开始的位置的数据进行替代。
* Replace the data at the beginning of the file.
*/
@Test
public void test1(){
try(RandomAccessFile af = new RandomAccessFile(new File("hi.txt"),"rw");){
af.write("我 ".getBytes());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
2、插入操作
/**
* 插入操作
* insert operation
*/
@Test
public void test2(){
try(RandomAccessFile rw = new RandomAccessFile("hi.txt","rw")) {
rw.seek(10);
StringBuffer stringBuffer = new StringBuffer((int) new File("hi.txt").length());
byte[] buffer = new byte[10];
int len = -1;
while((len = rw.read(buffer)) != -1){
stringBuffer.append(new String(buffer,0,len)); // 通过toString会导致中文无法解析。
}
//调用指针,写入“xyz”
rw.seek(10);
rw.write("xyz".getBytes());
rw.write(stringBuffer.toString().getBytes());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}