3

RandomAccessFile随机读写文件

 2 years ago
source link: https://perkins4j2.github.io/posts/32311/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

RandomAccessFile随机读写文件

发表于

2020-08-31

| 分类于 架构

| 阅读次数: 36

本文字数: 1.3k

|

阅读时长 ≈ 1 分钟

RandomAccessFile提供了对文件的读写功能。RandomAccessFile 虽然属于java.io下的类,但它不是InputStream或者OutputStream的子类;它也不同于FileInputStream和FileOutputStream。

FileInputStream 只能对文件进行读操作,而FileOutputStream 只能对文件进行写操作;但是,RandomAccessFile 与输入流和输出流不同之处就是RandomAccessFile可以访问文件的任意地方同时支持文件的读和写,并且它支持随机访问。

RandomAccessFile包含InputStream的三个read方法,也包含OutputStream的三个write方法。同时RandomAccessFile还包含一系列的readXxx和writeXxx方法完成输入输出。
   RandomAccessFile父类:java.lang.Object
   所有接口实现:Closeable, DataInput, DataOutput, AutoCloseable

  1、向10G文件末尾插入指定内容,或者向指定指针位置进行插入或者修改内容。
  2、断点续传,使用seek()方法不断的更新下载资源的位置。

long getFilePoint():设置文件指针偏移,从该文件的开头测量,发生下一次读取或写入。(前面是文档原文翻译通俗一点就是:返回文件记录指针的当前位置,不指定指针的位置默认是0。)

void seek(long pos):设置文件指针偏移,从该文件的开头测量,发生下一次读取或写入。(前面是文档原文翻译通俗一点就是:将文件记录指针定位到pos位置。)

通过指定记录指针的位置及跳过的字节数,输出内容

raf = new RandomAccessFile(path,mode);
raf.writeBytes("If you interesting to me,please give the kiss to me!");
raf.seek(seek);//指定记录指针的位置
//System.out.println(raf.readLine());//使用seek指针指向0,readLine读取所有内容
raf.getFilePointer();//获取指针的位置
raf.skipBytes(skipBytes);//跳过的字节数

在内容后面插入一个字符串,并输出

raf = new RandomAccessFile(path,mode);
raf.writeBytes("If you interesting to me,please give the kiss to me!");
raf.seek(raf.length());//通过raf.length()获取总长度,记录指针指向最后
raf.write("oh yes!".getBytes());//在最后插入oh yes!s
raf.seek(0);//记录指针指向初始位置
------ 本文结束------

本文标题:RandomAccessFile随机读写文件

文章作者:Perkins

发布时间:2020年08月31日

原始链接:https://perkins4j2.github.io/posts/32311/

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK