16.6 RandomAccessFile

RandomAccessFile可以實現文件數據的隨機讀取,即:通過對文件內部讀取位置的自由定義,以實現部分數據的讀取操作,所以在使用此類操作時就必須保證寫入數據時數據格式與長度統一
在這裏插入圖片描述
在這裏插入圖片描述
範例:使用RandomAccessFile寫入數據

package com.lxh.sixteenchapter;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;

public class JavaIODemo421 {
       public static void main(String[] args) {
		File file=new File("E:"+File.separator+"File"+File.separator+"ll.txt");
		if(!file.exists()) {
			try {
				file.createNewFile();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		try {
			RandomAccessFile raf=new RandomAccessFile(file,"rw");
			//要保存的姓名數據,爲保證長度一致,使用空格填充
			String name[]=new String[]{"zhangsan","lisi    ","wangwu  "};
			int age[]=new int [] {17,23,40};
			//循環寫入
			for(int x=0;x<name.length;x++) {
				raf.write(name[x].getBytes());
				raf.writeInt(age[x]);
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

範例:使用RandomAccessFile讀取數據

package com.lxh.sixteenchapter;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;

public class JavaIODemo422 {
    public static void main(String[] args) {
    	File file=new File("E:"+File.separator+"File"+File.separator+"ll.txt");
    	RandomAccessFile raf=null;
    	try {
			raf=new RandomAccessFile(file,"rw");
		
			{
		    	//讀取王五的數據,跳過24位
			    raf.skipBytes(24);
			    byte data[]=new byte[8];
			    int len=raf.read(data);
			    System.out.println("姓名:"+new String(data,0,len).trim()+"年齡:"+raf.readInt());
			}
			
			{
				//讀取李四的數據,回跳12位
			    raf.seek(12);
			    byte data[]=new byte[8];
			    int len=raf.read(data);
			    System.out.println("姓名:"+new String(data,0,len).trim()+"年齡:"+raf.readInt());
			}
			{
				//讀取張三的數據,回跳到開始點
			    raf.seek(0);
		     	byte data[]=new byte[8];
		     	int len=raf.read(data);
		    	System.out.println("姓名:"+new String(data,0,len).trim()+"年齡:"+raf.readInt());
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			if(raf!=null) {
				try {
					raf.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
}

執行結果

姓名:wangwu年齡:40
姓名:lisi年齡:23
姓名:zhangsan年齡:17
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章