Java基础之File(二)

RandomAccessFile

java.io.RandomAccessFile
用来读写文件的数据
raf是基于指针进行读写数据的,即总是在指针指向的位置读写字节,并且读写后会自动后移。

RandomAccessFile的构造函数

RandomAccessFile raf = new RandomAccessFile(File file, String mode);
此处的mode有四个值,分别为 r, rw, rws, rwd

  1. r
    以只读的方式打开文本,也就意味着不能用write来操作文件
  2. rw
    读操作和写操作都是允许的
  3. rws
    每当进行写操作,同步的刷新到磁盘,刷新内容和元数据
  4. rwd
    每当进行写操作,同步的刷新到磁盘,刷新内容

好吧,我承认rws和rwd我没用到,一般就r和rw。

常用方法

  1. read() 读取一个字节
  2. read(byte[] b) 读取一个字节数组
  3. write() 写入一个字节
  4. write(byte[] b) 写入一个字节数组
  5. write(byte[] b,int off,int len); 写入一个数组,从数组的off处,读取len个字节
  6. length() 返回文件的长度,返回类型为long
  7. seek() 指定光标的位置
  8. getFilePointer() 返回光标的位置
  9. readDouble() readFloat() readBoolean() readInt() readLong() readShort() readByte() readChar()
    读取基本数据类型,这里有可能出现异常,比如readInt() 表示读取一个int值,即四个字节,如果光标处以后没有四个字节,则会出现EOFException,即end of file exception,表示已经读到文件末尾但没有读取到足够的字节数。
    10.writeDouble() writeFloat() writeBoolean() writeInt() writeLong() writeShort() writeByte() writeChar()
    写入基本数据类型

示例

用RandomAccessFile复制文件

/**
 * RandomAccessFile 复制文件
 * @author ZDL
 *
 */
public class IOLearn3 {
	public static void main(String[] args) throws IOException {
		File file1 = new File("D://test.ts");
		File file2 = new File("D://test2.ts");
		RandomAccessFile raf1 = new RandomAccessFile(file1, "r");
		RandomAccessFile raf2 = new RandomAccessFile(file2, "rw");
		long start = System.currentTimeMillis();
		//10K 听说是效率极佳的状态
		byte[] b = new byte[1024*10];
		int len = -1;//读取到的字节长度
		while((len = raf1.read(b))!=-1){//读取到数据,如果为-1则表示读到文件的末尾
			raf2.write(b,0,len);
		}
		raf1.close();
		raf2.close();
		long end = System.currentTimeMillis();
		System.out.println("复制完毕!耗时:"+(end-start)+" ms");
	}
}

在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值