1. 程式人生 > >java以位元組流形式讀寫檔案

java以位元組流形式讀寫檔案

java中以位元組流的形式讀取檔案採用的是FileInputStream,將指定路徑的檔案以位元組陣列的形式迴圈讀取,程式碼如下:
public void ReadFileByByte(String path){
		try {
			int length = 0;
			byte[] Buff = new byte[1024];
			File file = new File(path);
			FileInputStream fis = new FileInputStream(file);
			
			while((length =fis.read(Buff))!=-1){
				//對Buff進行處理	
			}
			 
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}catch (IOException ex) {
			// TODO Auto-generated catch block
			ex.printStackTrace();
		}finally{
if(fis!=null){
fis.close();
}
}
	}
	

java中以位元組流的形式寫入檔案採用的是FileOutputStream,在指定路徑下寫入指定位元組陣列內容,並可設定追加模式或者覆蓋模式,程式碼如下:

public void WriteFileByByte(String path,byte[] contents,boolean isAppend){
		try {
			int length = contents.length;
			FileOutputStream fos = new FileOutputStream(path,isAppend);//isAppend如果為true,為追加寫入,否則為覆蓋寫入
			
			fos.write(contents,0,length);//表示把位元組陣列contents的從下標0開始寫入length長度的內容
			 
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}catch (IOException ex) {
			// TODO Auto-generated catch block
			ex.printStackTrace();
		}finally{
			if(fos!=null){
				fos.close();
			}
		}
}