歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Java從文件指定位置開始讀取文件流

Java從文件指定位置開始讀取文件流

日期:2017/3/1 9:51:17   编辑:Linux編程

Java從文件指定位置開始讀取文件流

文件任意位置讀取
一般有兩種方法:
1、使用FileInputStream類 , skip指定位置
2、使用RandomAccessFile類,seek指定位置

此處先說一下第一種方法,直接看測試代碼:

public static void read(){
long from = 4+1;//從該字節開始讀,自己測注意中文是兩個字節
try{
File file = new File("d:\\文件上傳\\ss.txt");
FileInputStream bis=new FileInputStream(file);
bis.skip(from-1);//文件指向前一字節
@SuppressWarnings("resource")
//指定文件位置讀取的文件流
InputStream sbs = new BufferedInputStream(bis);
//存入文件,以便檢測
File file1=new File("d:\\文件上傳\\ss1.txt");
OutputStream os=null;
try
{
os=new FileOutputStream(file1);
byte buffer[]=new byte[4*1024];
int len = 0;
while((len = sbs.read(buffer)) != -1)//
{
os.write(buffer,0,len);
}
os.flush();
}catch(Exception e){
e.printStackTrace();
}finally{
try {
os.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}catch(FileNotFoundException e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}finally{
}
}


主要代碼:

long from = 4+1;//從該字節開始讀,自己測注意中文是兩個字節
File file = new File("d:\\文件上傳\\ss.txt");
FileInputStream bis=new FileInputStream(file);
bis.skip(from-1);//文件指向前一字節

@SuppressWarnings("resource")
//指定文件位置讀取的文件流
InputStream sbs = new BufferedInputStream(bis); //得到指定位置的流

也可以獲得指定長度的文件
第二種方法後續上傳

Copyright © Linux教程網 All Rights Reserved