标签:[] 覆盖 地方 sys 同步 ack top 映射文件 演示
RandomAccessFile 是不属于 InputStream 和 OutputStream 类系的(既可以输入也可以输出),它的唯一父类是 Object
// 文本文件的复制(实现读写)
@Test
public void test1() {
RandomAccessFile rafin = null;
RandomAccessFile rafout = null;
try {
rafin = new RandomAccessFile("C:/Users/59929/Desktop/test1.txt", "r");
rafout = new RandomAccessFile("C:/Users/59929/Documents/test.txt", "rw");
int len;
byte[] b = new byte[1024];
while ((len = rafin.read(b)) != -1) {
rafout.write(b, 0, len);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (rafout != null) {
try {
rafout.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (rafin != null) {
try {
rafin.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
// 实现文本文件的插入操作
@Test
public void test2() {
RandomAccessFile raf = null;
try {
raf = new RandomAccessFile("C:/Users/59929/Desktop/test2.txt", "rw");
System.out.println("现在指针位置为:" + raf.getFilePointer());
raf.seek(16);
System.out.println("移到要修改的位置,现在指针位置为:" + raf.getFilePointer());
int len;
byte[] b = new byte[10];
StringBuffer sb = new StringBuffer();
while ((len = raf.read(b)) != -1) {
sb.append(new String(b, 0, len));
}
System.out.println("读完后现在指针位置为:" + raf.getFilePointer());
raf.seek(16);
System.out.println("再次移到要修改的位置,现在指针位置为:" + raf.getFilePointer());
raf.write("c".getBytes());
raf.write(sb.toString().getBytes());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (raf != null) {
try {
raf.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
标签:[] 覆盖 地方 sys 同步 ack top 映射文件 演示
原文地址:http://www.cnblogs.com/chendifan/p/6537811.html