Java文件 ---RandomAccessFile示例

RandomAccessFile是用来访问那些保存数据记录的文件的,你就可以用seek( )方法来访问记录,并进行读写了。这些记录的大小不必相同;但是其大小和位置必须是可知的。但是该类仅限于操作文件

MulitWriteFile类:程序入口——写入数据、读取数据

public class MulitWriteFile {
    
    static File file = new File("RandomAccessFile.txt");

    public static void main(String[] args) {
        
        /* 与线程结合向文件中写入数据 */
        if (file.exists()) {
            file.delete();
        }
        new WriteFile(file, 5).start();
        new WriteFile(file, 3).start();
        new WriteFile(file, 1).start();
        new WriteFile(file, 4).start();
        new WriteFile(file, 2).start();
        
        /* 读取文件指定位置的数据 */
        RandomAccessFile raf = null;
        try {
            raf = new RandomAccessFile(file, "r");
            raf.seek(300);
            byte[] str = new byte[20];
            raf.read(str);
            String in = new String(str);
            System.out.println(in);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            try {
                if (raf != null) {
                    raf.close();
                }
            } catch (Exception e) {
            }
        }
    }
}

 

WriteFile类(线程):RandomAccessFile用法——向文件指定位置写入数据

public class WriteFile extends Thread {

    /** 要写入的文件 */
    File file;
    /** 要插入的区块(位置) */
    int block;
    /** 一个区块的长度 */
    int L = 100;
    
    /**
     * File
     *            |***        |+++
     * |-----------***---------+++--------------------------|
     *         |---
     */
    
    /**
     * 1            2            3            4            5(2)
     * |------------|------------|------------|------------|------------|
     * 0xL            1xL
     * 
     * @param f
     * @param b
     */

    public WriteFile(File f,int b){
        file = f;
        block = b;
    }
    
    @Override
    public void run() {
        RandomAccessFile raf = null;
        try {
            // 得到需要读写的文件
            raf = new RandomAccessFile(file, "rw");
            // 将指针移动到指定位置
            raf.seek((block-1)*L);
            // 从指定位置开始写入数据
            raf.writeBytes("This is block"+block);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            if (raf != null) {
                try {
                    raf.close();
                } catch (Exception e) {
                }
            }
        }
    }
}
posted @ 2017-10-30 21:50  小白知浅  阅读(291)  评论(0编辑  收藏  举报