RandomAccessFile方法使用测试


public class Test {
public static void main(String[] args) throws IOException, InterruptedException {
test1();
// test2();
test3();
}

private static void test1() throws IOException{

String filePath = "F:/shanch/temp/a.txt";

//RandomAccessFile没有会自动创建文件
RandomAccessFile raFile = new RandomAccessFile(filePath,"rw");
System.out.println(raFile.getFilePointer());

//setLength会往文件里面写入空白串 即byte 00
raFile.setLength(36);

raFile.writeBytes("0123456789abcdefghijklmnopqrstuvwxyz1111");

System.out.println(raFile.getFilePointer());

//会将多出的1111截掉
raFile.setLength(36);
System.out.println(raFile.getFilePointer());

raFile.seek(20);
System.out.println(raFile.getFilePointer());

raFile.skipBytes(6);
System.out.println(raFile.getFilePointer());

//skipbytes不会使指针将超过文件长度
raFile.skipBytes(20);
System.out.println(raFile.getFilePointer());

//seek如果位置超过文件长度,会将文件扩大
raFile.seek(50);
System.out.println(raFile.getFilePointer());
raFile.write(100);

raFile.setLength(36);

}

private static void test2() throws IOException{

String filePath = "F:/shanch/temp/a.txt";
RandomAccessFile raFile = new RandomAccessFile(filePath,"rw");

raFile.seek(10);
//read读取当前指针的byte 读取之后指针下移一个byte
System.out.println((char)raFile.read());
System.out.println(raFile.getFilePointer());

raFile.seek(10);
raFile.write(0);//替换a 而非插入
raFile.write(0);//替换b
raFile.write(0);//替换c
}

private static void test3() throws IOException, InterruptedException{

final String filePath = "F:/shanch/temp/a.txt";
RandomAccessFile raFile = new RandomAccessFile(filePath,"rw");
FileChannel fChannel = raFile.getChannel();

//当文件锁住时,不可修改
// fChannel.lock();
//程序退出时会自动释放锁

//position与FilePointer一致
fChannel.position(10);
System.out.println(raFile.getFilePointer());
raFile.seek(20);
System.out.println(fChannel.position());

//清空文件,从文件头开始,只保留指定字节数
fChannel.truncate(50);

fChannel.lock(10, 10, true);
//FileChannel与RandomAccessFile的写方法是不同的实现
//FileChannel锁住时,RandomAccessFile将不能写
// raFile.seek(15);
// raFile.write(97); //此处会报异常

Thread.currentThread().sleep(2000);
new Thread() {
public void run(){
try
{
RandomAccessFile raFile = new RandomAccessFile(filePath,"rw");
raFile.seek(15);
System.out.println((char)raFile.read());
raFile.write(26);//另一个程序已锁定文件的一部分,进程无法访问。
// raFile.read();
}
catch (IOException e1)
{
e1.printStackTrace();
}
}
}.start();

}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值