RandomAccessFile操作文件

 1 package file;
 2 
 3 import java.io.File; 
 4 import java.io.FileInputStream;
 5 import java.io.FileOutputStream;
 6 import java.io.IOException;
 7 import java.io.RandomAccessFile;
 8 
 9 
10 public class InsertContent {
11 
12     public static void insert(String fileName,long pos,String insertContent) throws IOException{
13         File tmp = File.createTempFile("tmp", null);
14         tmp.deleteOnExit();
15         try(
16             RandomAccessFile raf = new RandomAccessFile(fileName, "rw");
17             FileOutputStream tmpOut = new FileOutputStream(tmp);
18             FileInputStream tmpInputStream = new FileInputStream(tmp)
19             ){
20             //  将记录指针移动文件末尾  追加内容
21 //            raf.seek(raf.length());
22             
23             // 将记录指针移动指定位置
24             raf.seek(pos);
25             
26             byte[] bbuf = new byte[64];
27         
28             int hasRead = 0;
29             
30             StringBuffer sbf = new StringBuffer();
31             
32             while((hasRead = raf.read(bbuf)) > 0 ){
33                 tmpOut.write(bbuf, 0 , hasRead);
34                 sbf.append(new String(bbuf));
35             }
36             System.out.println(sbf.toString());
37             
38             raf.seek(pos);
39             
40             raf.write(insertContent.getBytes());
41             
42             while ((hasRead = tmpInputStream.read(bbuf)) > 0) {
43                 raf.write(bbuf , 0 , hasRead);
44             }
45         }
46     }
47     
48     public static void main(String[] args) {
49         try {
50             insert("f:/new 1.txt", 45, "ajsdkjfksldjfkl");
51         } catch (IOException e) {
52             e.printStackTrace();
53         }
54     }
55 }

 

转载于:https://www.cnblogs.com/zfy0098/p/5241078.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值