Java IO流->处理流->“随机访问” 的方式:RandomAccessFile

来源:互联网 发布:网络很丑的女人的图片 编辑:程序博客网 时间:2024/05/21 11:10

图一:

图二:

示例代码:

import java.io.File;import java.io.FileNotFoundException;import java.io.IOException;import java.io.RandomAccessFile;import org.junit.Test;public class TestRandomAccessFile {//进行文件的读写@Testpublic 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();}}}}//实际上实现的是覆盖操作@Testpublic 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()更好的实现了插入操作@Testpublic 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(),更通用@Testpublic 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();}}}}}


0 0
原创粉丝点击