首页 > 数据库技术 > 详细

RandomAccessFile操作文件

时间:2016-03-04 10:27:46      阅读:180      评论:0      收藏:0      [点我收藏+]
 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 }

 

RandomAccessFile操作文件

原文:http://www.cnblogs.com/zfy0098/p/5241078.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!