在隨機流中如何定義起始索引和設置讀取文件的大小

<code>package cn.jd.io;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;

public class RandTest03 {
\t\tpublic static void main(String[] args) throws IOException {
\t\t\tRandomAccessFile raf=new RandomAccessFile(new File("src/cn/jd/io/Copy.java"), "r");
\t\t\t//起始位置
\t\t\tint beginPos=2;
\t\t\t//實際大小
\t\t\tint actualSize=1026;//我要讀取1026個字節
\t\t\t//隨機讀取
\t\t\traf.seek(beginPos); //從第二個索引開始讀取,記住索引是從0開始的
\t\t\t//讀取 讀取方式和字節流的讀取方式是一樣的
\t\t\tbyte[] flush=new byte[1024];
\t\t\tint len=-1;
\t\t\twhile((len=raf.read(flush))!=-1) {
\t\t\t\t
\t\t\t\tif(len<=actualSize) {//獲取本次讀取的所有內容
\t\t\t\t\tSystem.out.println(new String(flush,0,len));
\t\t\t\t\tactualSize-=len;//還剩餘多少字節需要下次讀取
\t\t\t\t}else {
\t\t\t\t\tSystem.out.println(new String(flush,0,actualSize));
\t\t\t\t\tbreak;
\t\t\t\t}
\t\t\t}
\t\t\t
\t\t\t
\t\t\traf.close();
\t\t}
\t\t
}
/<code>



分享到:


相關文章: