0
点赞
收藏
分享

微信扫一扫

随机流


随机流

  • ​​一、介绍​​
  • ​​二、RandomAccessFile的使用​​
  • ​​三、代码​​
  • ​​RandomAccessFileTest 类​​

总结于​​尚硅谷​​学习视频

一、介绍

随机流_输出流


随机流_输出流_02

二、RandomAccessFile的使用

1.RandomAccessFile直接继承与java.lang.Object类,实现了DataInput 和DataOutput接口
2.RandomAccessFile既可以作为一个输入流有可以作为一个输出流

3.如果RandomAccessFile 作为输出流时,写出到的文件如果不存在,则在执行的过程中自动创建
如果写出到的文件存在,则会对原有的文件内容进行覆盖。(默认情况下,从头覆盖)

4.可以根据相关操作,实现RandomAccessFile”插入“数据的效果

三、代码

RandomAccessFileTest 类

package com.day0317_2;

import org.junit.jupiter.api.Test;

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

/**
* RandomAccessFile的使用
* 1.RandomAccessFile直接继承与java.lang.Object类,实现了DataInput 和DataOutput接口
* 2.RandomAccessFile既可以作为一个输入流有可以作为一个输出流
*
* 3.如果RandomAccessFile 作为输出流时,写出到的文件如果不存在,则在执行的过程中自动创建
* 如果写出到的文件存在,则会对原有的文件内容进行覆盖。(默认情况下,从头覆盖)
*
* 4.可以根据相关操作,实现RandomAccessFile”插入“数据的效果
*/


public class RandomAccessFileTest {

@Test
public void test1() {

RandomAccessFile raf1= null;
RandomAccessFile raf2= null;
try {
//1
raf1 = new RandomAccessFile(new File("图片.png"),"r");
raf2 = new RandomAccessFile(new File("图片4.png"),"rw");

//2
byte[] buffer=new byte[1024];
int len;

while ((len=raf1.read(buffer))!=-1){
raf2.write(buffer,0,len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
//3
if (raf1!=null)
try {
raf1.close();
} catch (IOException e) {
e.printStackTrace();
}
if (raf2!=null)
try {
raf2.close();
} catch (IOException e) {
e.printStackTrace();
}
}


}

@Test
public void test2()throws IOException{
RandomAccessFile raf1=new RandomAccessFile("hello6.txt","rw");

raf1.seek(3);//将指针调到角标为3的位置
raf1.write("xyz".getBytes());//

raf1.close();
}

/*
使用RandomAccessFile实现数据的插入效果
*/
@Test
public void test3()throws IOException{
RandomAccessFile raf1=new RandomAccessFile("hello6.txt","rw");

raf1.seek(3);//将指针调到角标为3的位置
//保存指针3后面的所有数据到StringBuilder中
StringBuilder builder=new StringBuilder((int) new File("hello.txt").length());
byte[] buffer=new byte[20];
int len;
while ((len=raf1.read(buffer))!=-1){
builder.append(new String(buffer,0,len));
}

//调回指针
raf1.seek(3);
raf1.writeBytes("xyz");

//将StringBuilder中的数据写入到文件中
raf1.write(builder.toString().getBytes());

raf1.close();
}

//思考:将StringBuilder替换为ByteArrayOutputStream


}


举报

相关推荐

0 条评论