RandomAccessFile使用小結

RandomAccessFile是Java輸入/輸出流體系中功能最豐富的文件內容訪問類,既可以讀取文件內容,也可以向文件輸出數據。

與普通的輸入/輸出流不同的是,RandomAccessFile支持跳到文件任意位置讀寫數據,RandomAccessFile對象包含一個記錄指針,用以標識當前讀寫處的位置,當程序創建一個新的RandomAccessFile對象時,該對象的文件記錄指針對於文件頭(也就是0處),當讀寫n個字節後,文件記錄指針將會向後移動n個字節。

除此之外,RandomAccessFile可以自由移動該記錄指針

RandomAccessFile包含兩個方法來操作文件記錄指針:

  • long getFilePointer():返回文件記錄指針的當前位置
  • void seek(long pos):將文件記錄指針定位到pos位置

RandomAccessFile類在創建對象時,除了指定文件本身,還需要指定一個mode參數,該參數指定RandomAccessFile的訪問模式,該參數有如下四個值:

  • r:以只讀方式打開指定文件。如果試圖對該RandomAccessFile指定的文件執行寫入方法則會拋出IOException
  • rw:以讀取、寫入方式打開指定文件。如果該文件不存在,則嘗試創建文件
  • rws:以讀取、寫入方式打開指定文件。相對於rw模式,還要求對文件的內容或元數據的每個更新都同步寫入到底層存儲設備,默認情形下(rw模式下),是使用buffer的,只有cache滿的或者使用RandomAccessFile.close()關閉流的時候兒才真正的寫到文件
  • rwd:與rws類似,只是僅對文件的內容同步更新到磁盤,而不修改文件的元數據

代碼1-1

import java.io.IOException;
import java.io.RandomAccessFile;
 
public class RandomAccessRead {
 
    public static void main(String[] args) {
        if (args == null || args.length == 0) {
            throw new RuntimeException("請輸入路徑");
        }
        RandomAccessFile raf = null;
        try {
            raf = new RandomAccessFile(args[0], "r");
            System.out.println("RandomAccessFile的文件指針初始位置:" + raf.getFilePointer());
            raf.seek(100);
            byte[] bbuf = new byte[1024];
            int hasRead = 0;
            while ((hasRead = raf.read(bbuf)) > 0) {
                System.out.print(new String(bbuf, 0, hasRead));
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            try {
                if (raf != null) {
                    raf.close();
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
 
}

代碼1-1運行結果:

root@lejian:/home/software/.io# cat article

Unexpected Benefits of Drinking Hot Water

Reasons To Love An Empowered Woman

Reasons Why It’s Alright To Feel Lost In A Relationship

Signs You’re Uber Smart Even If You Don’t Appear to Be

Differences Between Positive People And Negative People

Sex Before Marriage: 5 Reasons Every Couple Should Do It

root@lejian:/home/software/.io# java RandomAccessRead article

RandomAccessFile的文件指針初始位置:0

ght To Feel Lost In A Relationship

Signs You’re Uber Smart Even If You Don’t Appear to Be

Differences Between Positive People And Negative People

Sex Before Marriage: 5 Reasons Every Couple Should Do It

代碼1-2使用RandomAccessFile來追加文件內容,RandomAccessFile先獲取文件的長度,再將指針移到文件的末尾,再將要插入的內容插入到文件

代碼1-2

import java.io.IOException;
import java.io.RandomAccessFile;
 
public class RandomAccessWrite {
 
    public static void main(String[] args) {
        if (args == null || args.length == 0) {
            throw new RuntimeException("請輸入路徑");
        }
        RandomAccessFile raf = null;
        try {
            String[] arrays = new String[] { "Hello Hadoop", "Hello Spark", "Hello Hive" };
            raf = new RandomAccessFile(args[0], "rw");
            raf.seek(raf.length());
            raf.write("追加內容:\n".getBytes());
            for (String arr : arrays) {
                raf.write((arr + "\n").getBytes());
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            try {
                if (raf != null) {
                    raf.close();
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
 
}

代碼1-2運行結果:

root@lejian:/home/software/.io# cat text

Hello spring

Hello Hibernate

Hello Mybatis

root@lejian:/home/software/.io# java RandomAccessWrite text

root@lejian:/home/software/.io# cat text

Hello spring

Hello Hibernate

Hello Mybatis

追加內容:

Hello Hadoop

Hello Spark

Hello Hive

RandomAccessFile如果向文件的指定的位置插入內容,則新輸出的內容會覆蓋文件中原有的內容。如果需要向指定位置插入內容,程序需要先把插入點後面的內容讀入緩衝區,等把需要的插入數據寫入文件後,再將緩衝區的內容追加到文件後面,代碼1-3爲在文件指定位置插入內容

代碼1-3

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
 
public class InsertContent {
 
    public static void main(String[] args) {
        if (args == null || args.length != 3) {
            throw new RuntimeException("請分別輸入操作文件、插入位置和插入內容");
        }
        FileInputStream fis = null;
        FileOutputStream fos = null;
        RandomAccessFile raf = null;
        try {
            raf = new RandomAccessFile(args[0], "rw");
            File tmp = File.createTempFile("tmp", null);
            tmp.deleteOnExit();
            fis = new FileInputStream(tmp);
            fos = new FileOutputStream(tmp);
            raf.seek(Long.parseLong(args[1]));
            byte[] bbuf = new byte[64];
            int hasRead = 0;
            while ((hasRead = raf.read(bbuf)) > 0) {
                fos.write(bbuf, 0, hasRead);
            }
            raf.seek(Long.parseLong(args[1]));
            raf.write("\n插入內容:\n".getBytes());
            raf.write((args[2] + "\n").getBytes());
            while ((hasRead = fis.read(bbuf)) > 0) {
                raf.write(bbuf, 0, hasRead);
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            try {
                if (fis != null) {
                    fis.close();
                }
                if (fos != null) {
                    fos.close();
                }
                if (raf != null) {
                    raf.close();
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
 
}

代碼1-3運行結果:

root@lejian:/home/software/.io# cat text

To love oneself is the beginning of a lifelong romance.

Change your life today. Don't gamble on the future, act now, without delay.

Health is the thing that makes you feel that now is the best time of the year.

The very essence of romance is uncertainty.

Your time is limited, so don’t waste it living someone else’s life.

root@lejian:/home/software/.io# java InsertContent text 100 "Success covers a multitude of blunders."

root@lejian:/home/software/.io# cat text

To love oneself is the beginning of a lifelong romance.

Change your life today. Don't gamble on the

插入內容:

Success covers a multitude of blunders.

future, act now, without delay.

Health is the thing that makes you feel that now is the best time of the year.

The very essence of romance is uncertainty.

Your time is limited, so don’t waste it living someone else’s life.

原文:https://www.cnblogs.com/baoliyan/p/6225842.html

 

 

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