Java的RandomAccessFile隨機檔案讀寫的簡單使用
阿新 • • 發佈:2019-01-10
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(); } } newwriteFile(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(); } } } classwriteFile 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(); } } }