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();
				}
			}
		}
	}
}


猜你喜欢

转载自blog.csdn.net/u013453970/article/details/48104403
今日推荐