1. 随机存取文件流

RandomAccessFile

2. 使用说明

  1. RandomAccessFile直接继承于java.lang.Object类,实现了DataInput和DataOutput接口
  2. RandomAccessFile既可以作为一个输入流,又可以作为一个输出流

  3. 如果RandomAccessFile作为输出流时,写出到的文件如果不存在,则在执行过程中自动创建。

如果写出到的文件存在,则会对原文件内容进行覆盖。(默认情况下,从头覆盖)

  1. 可以通过相关的操作,实现RandomAccessFile“插入”数据的效果。seek(int pos)

3. 代码实现

典型代码1:

  1. @Test
  2. public void test1() {
  3. RandomAccessFile raf1 = null;
  4. RandomAccessFile raf2 = null;
  5. try {
  6. raf1 = new RandomAccessFile(new File("爱情与友情.jpg"),"r");
  7. raf2 = new RandomAccessFile(new File("爱情与友情1.jpg"),"rw");
  8. byte[] buffer = new byte[1024];
  9. int len;
  10. while((len = raf1.read(buffer)) != -1){
  11. raf2.write(buffer,0,len);
  12. }
  13. } catch (IOException e) {
  14. e.printStackTrace();
  15. } finally {
  16. if(raf1 != null){
  17. try {
  18. raf1.close();
  19. } catch (IOException e) {
  20. e.printStackTrace();
  21. }
  22. }
  23. if(raf2 != null){
  24. try {
  25. raf2.close();
  26. } catch (IOException e) {
  27. e.printStackTrace();
  28. }
  29. }
  30. }
  31. }

典型代码2:

/*
使用RandomAccessFile实现数据的插入效果
 */
@Test
public void test3() throws IOException {

    RandomAccessFile raf1 = new RandomAccessFile("hello.txt","rw");

    raf1.seek(3);//将指针调到角标为3的位置
    //保存指针3后面的所数据到StringBuilder中
    StringBuilder builder = new StringBuilder((int) new File("hello.txt").length());
    byte[] buffer = new byte[20];
    int len;
    while((len = raf1.read(buffer)) != -1){
        builder.append(new String(buffer,0,len)) ;
    }
    //调回指针,写入“xyz”
    raf1.seek(3);
    raf1.write("xyz".getBytes());

    //将StringBuilder中的数据写入到文件中
    raf1.write(builder.toString().getBytes());

    raf1.close();

    //思考:将StringBuilder替换为ByteArrayOutputStream
}
    // 将StringBuilder替换为ByteArrayOutputStream
    @Test
    public void test4() {

        RandomAccessFile raf = null;
        ByteArrayOutputStream baos = null;
        try {
            raf = new RandomAccessFile("hello.txt", "rw");

            raf.seek(3);

            baos = new ByteArrayOutputStream();

            int len;
            byte[] buff = new byte[20];

            while ((len = raf.read(buff)) != -1) {
                baos.write(buff, 0, len);
            }

            raf.seek(3);
            raf.write("123".getBytes());

            raf.write(baos.toByteArray());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {

            try {
                if (baos != null)
                    baos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (raf != null)
                    raf.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }