Java IO流->處理流->“隨機訪問” 的方式:RandomAccessFile

圖一:

圖二:

示例代碼:

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

import org.junit.Test;

public class TestRandomAccessFile {
	//進行文件的讀寫
	@Test
	public void test1() {
		RandomAccessFile raf1 = null;
		RandomAccessFile raf2 = null;
		try {
			raf1 = new RandomAccessFile(new File("hello.txt"), "r");
			raf2 = new RandomAccessFile("hello1.txt", "rw");
			
			byte[] b = new byte[20];
			int len;
			while((len = raf1.read(b)) != -1) {
				raf2.write(b, 0, len);
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if(raf2 != null) {
				try {
					raf2.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if(raf1 != null) {
				try {
					raf1.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	//實際上實現的是覆蓋操作
	@Test
	public void test2() {
		RandomAccessFile raf = null;
		try {
			raf = new RandomAccessFile("hello.txt", "rw");
			
			//先定位到要插入的地方
			raf.seek(4);
			raf.write("xy".getBytes());
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if(raf != null) {
				try {
					raf.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	//插入操作:通過進行復制操作,再進行覆蓋操作,test4()更好的實現了插入操作
	@Test
	public void test3() {
		RandomAccessFile raf = null;
		try {
			raf = new RandomAccessFile("hello.txt", "rw");
			raf.seek(4);
			String str = raf.readLine();
			
			raf.seek(4);
			raf.write("xy".getBytes());
			raf.write(str.getBytes());
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if(raf != null) {
				try {
					raf.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	//插入操作:相較於test3(),更通用
	@Test
	public void test4() {
		RandomAccessFile raf = null;
		try {
			raf = new RandomAccessFile("hello.txt", "rw");
			raf.seek(4);
			
			byte[] b = new byte[20];
			int len;
			StringBuffer sb = new StringBuffer();
			while((len = raf.read(b)) != -1) {
				sb.append(new String(b, 0, len));
			}
			raf.seek(4);
			raf.write("xy".getBytes());
			raf.write(sb.toString().getBytes());
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if(raf != null) {
				try {
					raf.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章