RandomAccessFile的使用

mac2022-06-30  19

/*

RandomAccessFile:支持随机访问1.既可以充当一个输入流,有可以充当一个输出流2.支持从文件的开头读取、写入3.支持从任意位置的读取、写入4.r表示只读 rw表示可读可写 w表示只写

*/

package day16; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.RandomAccessFile; import org.junit.Test; /* * RandomAccessFile:支持随机访问 * 1.既可以充当一个输入流,有可以充当一个输出流 * 2.支持从文件的开头读取、写入 * 3.支持从任意位置的读取、写入 * */ public class TestRandomAccessFile { @Test public void test1() { RandomAccessFile raf1 = null; RandomAccessFile raf2 = null; try { raf1 = new RandomAccessFile(new File("test.txt"), "r"); raf2 = new RandomAccessFile(new File("test1.txt"),"rw"); byte[] b = new byte[20]; int len; if((len = raf1.read(b)) != -1) { raf2.write(b,0,len); } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally { if(raf1 != null) { try { raf1.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }if(raf1 != null) { try { raf2.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } //实现插入的效果 @Test public void test4() { RandomAccessFile raf = null; try { raf = new RandomAccessFile(new File("test1.txt"),"rw"); raf.seek(0); raf.write("柚柚妹卢本伟牛逼".getBytes()); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { if(raf != null) { try { raf.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } @Test public void test5() { RandomAccessFile raf = null; try { raf = new RandomAccessFile(new File("test.txt"),"rw"); raf.seek(1); String str = raf.readLine(); long l = raf.getFilePointer(); raf.seek(1); raf.write("xy".getBytes()); raf.write(str.getBytes()); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { if(raf != null) { try { raf.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } //相较于test4更通用 @Test public void test3() { RandomAccessFile raf = null; try { raf = new RandomAccessFile(new File("test.txt"),"rw"); raf.seek(13); byte[] b = new byte[20]; int len; StringBuffer sb = new StringBuffer(); while((len = raf.read(b)) != -1) { sb.append(new String(b,0,len)); } long l = raf.getFilePointer(); raf.seek(13); raf.write("xy".getBytes()); raf.write(sb.toString().getBytes()); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { if(raf != null) { try { raf.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } }
最新回复(0)