随机存取文件流的使用示例

随机存取文件流的使用

package com.random;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;

import org.junit.Test;

// 随机存取文件流的使用
public class RandomAccessFileTest {
	// 在指定位置添加内容,原位置后的内容顺移
	@Test
	public void test03() throws IOException {
		// 创建随机访问流
		File file = new File("access.txt");
		RandomAccessFile raf = new RandomAccessFile(file, "rw");
		// 读取一行数据
		String line = raf.readLine();
		// 从读取到的数据中查找第一个字母o出现的位置
		int index = line.indexOf("o");
		
		// 设置读写内容的位置
		raf.seek(index+1);
		
		byte[] buf = new byte[5];
		int len;
		// 存储指定位置后的内容
		String str = "";
		while((len = raf.read(buf)) != -1) {
			str += new String(buf, 0, len);
		}
		
		// 再次定义指针
		raf.seek(index+1);
		
		raf.write("java".getBytes());
		raf.write(str.getBytes());
		
		raf.close();
	}
	
	// 以追加的方式写出文件
	@Test
	public void test02() throws IOException {
		File file = new File("access.txt");
		long pos = file.length();
		RandomAccessFile raf = new RandomAccessFile(file, "rw");
		raf.seek(pos);
		raf.write("java".getBytes());
		raf.close();
	}
	
	// 写出文件
	@Test
	public void test01() throws IOException {
		RandomAccessFile raf = new RandomAccessFile(
				new File("access.txt"), "rw");
		raf.write("hello".getBytes());
		//raf.seek(2);
		//raf.write("xx".getBytes());
		raf.close();
	}
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值