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(); } } }
Java的RandomAccessFile随机文件读写的简单使用
最新推荐文章于 2024-07-15 22:55:18 发布