java使用randomaccessfile在文件任意位置写入数据
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
public class InsertContent {
public static void insert(String fileName, long pos, String insertContent) throws IOException{
File file = File.createTempFile("tmp", null);
file.deleteOnExit();
RandomAccessFile raf = new RandomAccessFile(fileName, "rw");
FileInputStream fileInputStream = new FileInputStream(file);
FileOutputStream fileOutputStream = new FileOutputStream(file);
raf.seek(pos);
byte[] buff = new byte[64];
int hasRead = 0;
while((hasRead = raf.read(buff)) > 0){
fileOutputStream.write(buff);
}
raf.seek(pos);
raf.write(insertContent.getBytes());
//追加文件插入点之后的内容
while((hasRead = fileInputStream.read(buff)) > 0){
raf.write(buff, 0, hasRead);
}
raf.close();
fileInputStream.close();
fileOutputStream.close();
}
public static void main(String[] args) throws IOException {
insert("F:\AttendanceActivity.java", 57, "插入的内容rn");
}
}
上一篇:详细分析java 动态代理
栏 目:JAVA代码
本文标题:java使用randomaccessfile在文件任意位置写入数据
本文地址:http://www.codeinn.net/misctech/34258.html


阅读排行
- 1Java Swing组件BoxLayout布局用法示例
- 2java中-jar 与nohup的对比
- 3Java邮件发送程序(可以同时发给多个地址、可以带附件)
- 4Caused by: java.lang.ClassNotFoundException: org.objectweb.asm.Type异常
- 5Java中自定义异常详解及实例代码
- 6深入理解Java中的克隆
- 7java读取excel文件的两种方法
- 8解析SpringSecurity+JWT认证流程实现
- 9spring boot里增加表单验证hibernate-validator并在freemarker模板里显示错误信息(推荐)
- 10深入解析java虚拟机




