使用随机存取文件流:RandomAccessFile实现文本文件内容的随机插入

比上一个博客的文章更加通用的代码如下:

补充:hello.txt文档内容:

abcdefg12345

adafe

123wwe

 

public class TestRandomAccessFile {
//相较于test3,更通用
@Test
public void test4(){
RandomAccessFile raf = null;
try {
raf = new RandomAccessFile(new File("hello.txt"),"rw");

raf.seek(4);
byte[] b = new byte[10];
int len;
StringBuffer sb = new StringBuffer();
while((len = raf.read(b)) != -1){
sb.append(new String(b,0,len));
}
raf.seek(4);
raf.write("xy".getBytes());
raf.write(sb.toString().getBytes());
}catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if(raf != null){
try {
raf.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
}
}
}
 

你可能感兴趣的:(【Java】)