package stream; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.RandomAccessFile; import org.junit.jupiter.api.Test; /* * RandomAccessFile: random read and write access streaming * Either an input stream or an output stream * R | w | d | s: Read | Write | update data | metadata updates * * W: is the beginning of the file content coverage * * */ 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 random access | insertion method * * */ @Test public void test2() throws IOException { RandomAccessFile raf1 = new RandomAccessFile("hello.txt", "rw"); /*raf1.seek(3); raf1.write("abc".getBytes()); */ /* * Use StringBuilder * */ StringBuilder sb = new StringBuilder((int)(new File("hello.txt").length())); raf1.seek ( 3L ); int len; byte [] Buffer = new new byte [ 20 is ]; // to save it back to the while ((len = raf1.read (Buffer)) = -! . 1 ) { sb.append(new String(buffer,0,len)); } raf1.seek ( 3L ); // converted to byte write raf1.write ( " Zhouen Jie " .getBytes ()); raf1.write(sb.toString().getBytes()); raf1.close(); } }
java foundation - random access streaming
Guess you like
Origin www.cnblogs.com/zsben991126/p/12160914.html
Recommended
Ranking