歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Java文件定位讀取

Java文件定位讀取

日期:2017/3/1 9:54:44   编辑:Linux編程

1. 使用RandomAccessFile對象的seek函數來實現
public void seek(long pos) throws IOException
RandomAccessFile randomAccessFile = newRandomAccessFile ("./chanel.txt", "r"); // Set the file position 離文件起始位置10字節處randomAccessFile.seek (10);System.out.println(randomAccessFile.readLine());

其中 pos 代表偏移量,pos = 0, 代表 文件起始位置,pos = 10 表示偏移文件起始位置的10個字節處。注意是字節為單位。一個ASCII 碼的代表一個字節,如'A' , 'a'。漢字代表兩個字節。

以下圖片是EditPlus,指示的,我理解一個字節占一個col 。


2. 使用FileChannel的position方法來實現
public abstract FileChannel position(long newPosition) throws IOException
其中newPosition與上面的pos含義一樣。
在使用FileChannel之前,必須先打開它。但是,我們無法直接打開一個FileChannel,
需要通過使用一個InputStream、OutputStream或RandomAccessFile來
獲取一個FileChannel實例。下面是通過RandomAccessFile打開FileChannel的示例
RandomAccessFile randomAccessFile = newRandomAccessFile ("./chanel.txt", "r"); FileChannel fileChannel = randomAccessFile.getChannel( );//Set the file position離文件起始位置10字節處 fileChannel.position (10);System.out.println(randomAccessFile.readLine());

Copyright © Linux教程網 All Rights Reserved