天天看點

NIO本地檔案讀寫和複制案例

1、往本地檔案中寫資料

要使用FileChannel來往本地檔案寫入資料,那麼首先需要得到一個FileChannel對象。

在jdk文檔中關于FIleChannel的說命中可以看到這樣一段話:

此類沒有定義打開現有檔案或建立新檔案的方法,以後的版本中可能添加這些方法。在此版本中,可從現有的

FileInputStream

FileOutputStream

RandomAccessFile

對象獲得檔案通道,方法是調用該對象的 getChannel 方法,這會傳回一個連接配接到相同底層檔案的檔案通道。

也就是說現在FileChannel的對象擷取需要通過現有的檔案流中擷取。

public static void main(String[] args) throws Exception {
        FileOutputStream fileOutputStream = new FileOutputStream("hello.txt");
        //獲得FileChannel對象
        FileChannel channel = fileOutputStream.getChannel();
        //建立Buffer對象,并指定容量大小為1024
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        //往buffer寫内容
        byteBuffer.put("hello,nio".getBytes());
        //翻轉buffer,使指針傳回到初始化的位置
        byteBuffer.flip();
        //把buffer資料寫入通道中
        channel.write(byteBuffer);
        //釋放資料
        fileOutputStream.close();
    }
           

運作結果:

NIO本地檔案讀寫和複制案例

2、從本地檔案裡讀資料

public static void main(String[] args) throws Exception {
        FileInputStream fileInputStream = new FileInputStream("hello.txt");
        //獲得通道對象
        FileChannel channel = fileInputStream.getChannel();
        //建立buffer對象
        ByteBuffer byteBuffer = ByteBuffer.allocate(fileInputStream.available());
        //從通道中讀取資料到buffer對象
        channel.read(byteBuffer);
        String string = new String(byteBuffer.array());
        System.out.println(string);
        fileInputStream.close();
    }
           

運作結果:

NIO本地檔案讀寫和複制案例

3、複制檔案

public static void main(String[] args) throws Exception {
        FileInputStream fileInputStream = new FileInputStream("hello.txt");
        FileOutputStream fileOutputStream = new FileOutputStream("copy.txt");
        //獲得通道對象
        FileChannel inChannel = fileInputStream.getChannel();
        FileChannel outChannel = fileOutputStream.getChannel();
        outChannel.transferFrom(inChannel,0,inChannel.size());

        fileOutputStream.close();
        fileInputStream.close();
    }
           

繼續閱讀