Java的RandomAccessFile随机文件读写的简单使用

import java.io.*;

/**
 * Created by cuboo on 2016/10/10.
 */
public class io {
    public static void main(String agrs[]){
        //写入数据
        File file = new File("test.txt");
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        new writeFile(file,6,50,"hello").start();
        new writeFile(file,1,50,"world").start();
        new writeFile(file,2,50,"this").start();
        new writeFile(file,3,50,"is - - - - - -").start();
        new writeFile(file,4,50,"block").start();

        //读取数据
        try {
            RandomAccessFile ra = new RandomAccessFile(file,"r");
            ra.seek(100);
            byte bys[] = new byte[10];
            ra.read(bys);
//            System.out.println(ra.readLine());
            System.out.println(new String(bys));

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

class writeFile extends Thread {
    File in;
    int block;  //块下标
    int length; //每个块的长度
    String text;
    writeFile(File in,int block,int length,String text){
        this.in = in;
        this.block = block;
        this.length = length;
        this.text = text;
    }

    @Override
    public void run() {
        try {
            RandomAccessFile ra = new RandomAccessFile(in,"rw");
            /*
            *  file in 的内容
            *  block 1          block  2            block  3
            * |...................|.....................|
            * |.......length......|........length.......|
             */
            ra.seek((block-1)*length);//指向block
            ra.writeBytes(text+block);
            ra.writeBytes("\n");
            ra.close();

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值