package stream; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.RandomAccessFile; import org.junit.jupiter.api.Test; /* * RandomAccessTile:隨機讀寫訪問流 * 既可以是輸入流,也可以是輸出流 * r|w|d|s:讀|寫|更新數據|元數據更新 * * w:是對開頭對文件內容進行覆蓋 * * */ public class RandomAccessFileTest { @Test public void test1(){ RandomAccessFile raf1 = null; RandomAccessFile raf2 = null; try { //1.流對象 raf1 = new RandomAccessFile(new File("hello.txt"),"r"); raf2 = new RandomAccessFile(new File("hello2.txt"),"rw"); //2.讀寫 byte[] buffer = new byte[1024]; int len; while((len = raf1.read(buffer))!=-1) { raf2.write(buffer,0,len); } } catch (Exception e) { e.printStackTrace(); } finally { try { if(raf1!=null) raf1.close(); } catch (Exception e) { e.printStackTrace(); } try { if(raf2!=null) raf2.close(); } catch (Exception e) { e.printStackTrace(); } } } /* * seek隨機訪問|插入方法 * * */ @Test public void test2() throws IOException { RandomAccessFile raf1 = new RandomAccessFile("hello.txt", "rw"); /*raf1.seek(3); raf1.write("abc".getBytes()); */ /* * 使用StringBuilder * */ StringBuilder sb = new StringBuilder((int)(new File("hello.txt").length())); raf1.seek(3L); int len; byte[] buffer = new byte[20]; while((len = raf1.read(buffer))!=-1) { sb.append(new String(buffer,0,len)); } raf1.seek(3L); raf1.write("xyz".getBytes()); raf1.write(sb.toString().getBytes()); raf1.close(); } }