java random read and write access method of flow and seek

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: Random Access access stream 
 * may be either an input stream or an output stream 
 * r | w | d | s : read | write | update data | metadata updates 
 *      
 * W: is the beginning of the covering of the contents of the file 
 * 
 * * / 

public  class RandomAccessFileTest { 
    
    @Test 
    public  void test1 () { 
        
        a RandomAccessFile Rafl = null ; 
        a 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();
    }
    
}

 

 

Guess you like

Origin www.cnblogs.com/zsben991126/p/11881233.html