java2_day05 IO流
package com.xin.java;
import org.junit.Test;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
/**
* Created with IntelliJ IDEA.
* User: xinxueqi
* Date: 2022/4/26 19:53
* Description:
* RandomAccessFile的使用
* 1. RandomAccessFile直接继承于java.lang.Object类,而不是四个抽象基类,
* 实现了Datalnput、DataOutput这两个接口,也就意味着这个类既可以读也可以写。
* 2. RandomAccessFile既可以作为一个输入流,又可以作为一个输出流。
* 3. RandomAccessFile作为输出流时,写出到的文件,如果不存在,则在执行过程中自动创建。
* 如果写出到的文件存在,则会对原有文件内容进行覆盖,(默认情况下从头覆盖)。
* 4. 可以通过相关操作,实现RandomAccessFile"插入"数据的效果
*/
public class RandomAccessFileTest {
@Test
public void test1() {
RandomAccessFile raf1 = null;
RandomAccessFile raf2 = null;
try {
raf1 = new RandomAccessFile(new File("king.jpg"), "r");
raf2 = new RandomAccessFile(new File("king1.jpg"), "rw");
byte[] buffer = new byte[1024];
int len;
while ((len = raf1.read(buffer)) != -1) { //要读取buffer
raf2.write(buffer, 0, len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
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(new File("hello.txt"), "rw");
// RandomAccessFile raf1 = new RandomAccessFile(new File("hello1.txt"), "rw"); //文件不存在,创建新的
byte[] bytes = new byte[10];
int len;
String s ="";
while((len = raf1.read(bytes)) != -1 ){
s = s + new String(bytes, 0, len); //字符转换成字符串
}
// raf1.seek(3); //将指针调到角标为3的位置,并进行内容覆盖
raf1.seek(s.length()); //将指针调到角标为结尾的位置
raf1.write("xyz".getBytes());
raf1.close();
}
/*
使用RandomAccessFile实现数据的插入效果
*/
@Test
public void test3() throws IOException {
RandomAccessFile raf1 = new RandomAccessFile(new File("hello.txt"), "rw");
int chang = 3; //定义从第几个角标插入
byte[] bytes = new byte[10];
int len;
String s ="";
// StringBuilder builder = new StringBuilder((int) new File("hello.txt").length());
while((len = raf1.read(bytes)) != -1 ){
s = s + new String(bytes, 0, len); //字符转换成字符串
// builder.append(new String(bytes, 0, len));
}
String substring = s.substring(chang); //截取字符
raf1.seek(chang);
raf1.write("uvw".getBytes()); //插入的字符
raf1.write(substring.getBytes()); //加上截取的字符串
raf1.close();
}
}
本文来自博客园,作者:{诺不克},转载请注明原文链接:https://www.cnblogs.com/xinxueqi/p/16196975.html
好好写代码,天天开心啊!
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· 没有源码,如何修改代码逻辑?
· PowerShell开发游戏 · 打蜜蜂
· 在鹅厂做java开发是什么体验
· WPF到Web的无缝过渡:英雄联盟客户端的OpenSilver迁移实战