Java学习 IO 随机访问文件 RandomAccessFile类

此类既可以读也可以写 但是都是针对于文件,不能针对其他节点流

RandomAccessFile不是IO体系的类 父类是Object

public class Demo {

	public static void main(String[] args) throws IOException, ClassNotFoundException {
		writeAcc();
		readAcc();
	}

	public static void readAcc() throws IOException {
		
		RandomAccessFile raf = new RandomAccessFile("C:\\Users\\悠悠华\\Desktop\\test\\ranacc.txt", "r");
		
		byte[] buf = new byte[1024];
		
		int len = raf.read(buf);
		System.out.println(new String(buf,0,len));
		
	}

	public static void writeAcc() throws IOException {
		
		RandomAccessFile raf = new RandomAccessFile("C:\\Users\\悠悠华\\Desktop\\test\\ranacc.txt", "rw");
		
		raf.write("这是测试this is test!".getBytes());
		
		raf.close();
		
	}
	


}

另外可以通过long getFilePointer()函数返回文件记录指针的位置

通过void seek(long pos) 可以将文件记录指针定位到pos的位置

 

public static void readAcc() throws IOException {
		
		RandomAccessFile raf = new RandomAccessFile("C:\\Users\\悠悠华\\Desktop\\test\\ranacc.txt", "r");
		
		byte[] buf = new byte[1024];
		
		int len = raf.read(buf);
		System.out.println(new String(buf,0,len));
		System.out.println("当前指针位置:"+raf.getFilePointer());
		
	}


结果:
这是测试this is test!
当前指针位置:21
public static void writeAcc() throws IOException {
		
		RandomAccessFile raf = new RandomAccessFile("C:\\Users\\悠悠华\\Desktop\\test\\ranacc.txt", "rw");
		
		raf.write("这是测试this is test!".getBytes());
		raf.seek(40);
		raf.write("再来一下:".getBytes());
		raf.close();
		
	}


如果再次使用readAcc()读取一次的话结果如下:

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值