java-裝飾流-隨機流
阿新 • • 發佈:2018-11-09
RandomAccessFile 隨機流:支援讀取和寫入
seek方法隨機訪問,可以對檔案進行分割
1.指定起始位置,讀取剩餘的所有內容
package cn.lesson.Burrfed;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
/**
* 隨機讀取和寫入流RandomAccessFile
* @author MacBook
*
*/
public class RandonTest01 {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
RandomAccessFile raf = new RandomAccessFile(new File("D:\\e- java\\DealWithIO\\src\\cn\\lesson\\Burrfed\\copy.java"),"r");
//隨機讀取
raf.seek(2);
//讀取
byte[] flush = new byte[1024];//緩衝容器
int len=-1 ;
while((len=raf.read(flush))!=-1) {
System.out.println(new String(flush,0,len));
}
raf.close();
}
}
2.分塊思想:起始、實際大小
package cn.lesson.Burrfed;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
/**
* 隨機讀取和寫入流RandomAccessFile
* @author MacBook
*
*/
public class RandonTest01 {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
RandomAccessFile raf = new RandomAccessFile(new File("D:\\e- java\\DealWithIO\\src\\cn\\lesson\\Burrfed\\copy.java"),"r");
//起始位置
int beginPos = 2;
//實際大小
int actualSize =1026;
//隨機讀取
raf.seek(beginPos);
//讀取
byte[] flush = new byte[1024];//緩衝容器
int len=-1;
while((len=raf.read(flush))!=-1) {
if(actualSize>len) {
System.out.println(new String(flush,0,len));
actualSize-=len;
}else {
System.out.println(new String(flush,0,actualSize));
break;
}
}
raf.close();
}
}
3.起始位置、實際大小、塊數
package cn.lesson.Burrfed;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
/**
* 隨機讀取和寫入流RandomAccessFile
* @author MacBook
*
*/
public class RandonTest01 {
public static void main(String[] args) throws IOException {
//分多少塊
File src = new File("D:/e- java/DealWithIO/src/cn/lesson/Burrfed/ConverTest01.java");
//總長度
long len =src.length();
//每一塊的大小
int blockSize = 101;
//需要多少塊
int size = (int)Math.ceil(len*1.0/blockSize);
// System.out.println(size);
//起始位置
int beginpos=0;
//實際大小
int actualSize = (int)(blockSize>len?len:blockSize);
for(int i =0;i<size;i++) {
beginpos=i*blockSize;
if(i==size-1) {//最後一塊
actualSize=(int)len;
}else {//其他的
actualSize=blockSize;
len-=actualSize;//剩餘量
}
System.out.println(i+"->"+beginpos+"->"+actualSize);
split(i,beginpos,actualSize);
}
}
/**
* 第i指定起始位置和實際長度
* @param i
* @param beginPos
* @param actualSize
* @throws IOException
*/
public static void split(int i,int beginPos,int actualSize ) throws IOException {
// TODO Auto-generated method stub
RandomAccessFile raf = new RandomAccessFile(new File("D:\\e- java\\DealWithIO\\src\\cn\\lesson\\Burrfed\\copy.java"),"r");
//起始位置
//實際大小
//隨機讀取
raf.seek(beginPos);
//讀取
byte[] flush = new byte[1024];//緩衝容器
int len=-1;
while((len=raf.read(flush))!=-1) {
if(actualSize>len) {
System.out.println(new String(flush,0,len));
actualSize-=len;
}else {
System.out.println(new String(flush,0,actualSize));
break;
}
}
raf.close();
}
}