RandomAccessFile流:隨機存取文件流,該類定義了一個記錄指針,通過移動指針可以訪問文件的任意位置,且對文件既可以讀也可以寫。使用該類的write方法對文件寫入時,實際上是一種覆蓋效果,即寫入的內容會覆蓋相應位置處的原有內容。
為了實現插入內容的效果,需要我們自行設計程序來實現。下面是筆者的程序設計。
[1] 程序設計
1 /*--------------------- 2 程序實現的功能: 3 ....//使用RandomAccessFile流設計一個類,實現在指定文件的指定位置插入指定的內容 4 ---------------------*/ 5 package pack01; 6 7 import java.io.*; 8 9 public class InsertContent { 10 11 private String filePath; //要操作的文件的路徑 12 private String content; //要插入的內容 13 private long position; //要插入的位置 14 15 //構造方法 16 public InsertContent(String path, String con, long pos) { 17 filePath = path; 18 content = con; 19 position = pos; 20 } 21 22 //設置要操作的文件的路徑 23 public void setFilePath(String path) { 24 filePath = path; 25 } 26 27 //設置要插入文件的內容 28 public void setContent(String con) { 29 content = con; 30 } 31 32 //設置要插入的位置 33 public void setPosition(long pos) { 34 position = pos; 35 } 36 37 //插入內容的具體實現方法 38 public void insertCon(){ 39 40 RandomAccessFile raf = null; 41 42 try { 43 44 raf = new RandomAccessFile(filePath, "rw"); //將隨機存取文件流連接到文件,訪問方式設置為可讀可寫 45 raf.seek(position); //指定插入的位置 46 47 //***************先將插入點后面的內容保存起來**************** 48 StringBuffer sb = new StringBuffer(); 49 byte[] b = new byte[100]; 50 int len; 51 while( (len=raf.read(b)) != -1 ) { 52 sb.append( new String(b, 0, len) ); 53 } 54 //................................................. 55 56 raf.seek(position); //重新設置插入位置 57 raf.write( content.getBytes() ); //插入指定內容 58 raf.write( sb.toString().getBytes() ); //恢復插入點后面的內容 59 60 } catch (IOException e) { 61 62 e.printStackTrace(); 63 64 } finally { 65 66 //關閉隨機存取文件流 67 try { 68 raf.close(); 69 } catch (IOException e) { 70 e.printStackTrace(); 71 } 72 } 73 } 74 75 //測試方法 76 public static void main(String[] args) { 77 78 InsertContent ic = new InsertContent("d:/JavaTest/file1.txt", "Java", 5); 79 ic.insertCon(); 80 } 81 }
[2] 運行效果
運行前:
運行后:
注:希望與各位讀者相互交流,共同學習進步。