IO流(二)用位元組流拷貝檔案和用過濾流拷貝檔案

2021-10-06 02:55:05 字數 1936 閱讀 5918

位元組流:fileinputstream   fileoutputstream

過濾流/處理流: 

轉換流:

用位元組流(管子)fileinputstream,fileoutputstream拷貝檔案:

void copyfile(file src, file target) throws ioexception 

if (!target.exists())

fileinputstream fis = new fileinputstream(src);// 檔案輸入流/讀,從檔案輸入/讀到記憶體

fileoutputstream fos = new fileoutputstream(target);// 檔案輸出流/寫,從記憶體輸出/寫到檔案

byte buf = new byte[1024];

int lenth = -1;

// 準備拷貝

long begin = system.currenttimemillis();

while ((lenth = fis.read(buf)) != -1)

// 拷貝結束

long end = system.currenttimemillis();

system.out.println(end - begin);

if (fis != null)

if (fos != null)

}

用過濾/處理流(管子加粗)拷貝檔案:不管怎麼包都要用到fileinputstream,fileoutputstream

在關閉流的時候要先關包裝流再關基本流

void copyfilebyfilter(file src, file target) throws ioexception 

// 拷貝結束

long end = system.currenttimemillis();

system.out.println(end - begin);

// 先關高階流

bis.close();

bos.close();

fis.close();

fos.close();

}

datainputstream   dataoutputstream:可以對具體的資料型別作處理

objectinputstream    objectoutputstream:讀寫物件,可 將物件寫入檔案,實現資料持久化

讀物件,當讀到檔案結束時,不是返回null而是報eofexception異常

void readobject() throws ioexception 

fileinputstream fis = new fileinputstream(file);

objectinputstream ois = new objectinputstream(fis);

object obj = null;

// 讀取物件,如果讀不到,並不是返回null,而是報乙個eofexception異常

try

} catch (eofexception |classnotfoundexception e)

ois.close();

fis.close();

}

首先要有乙個emp物件類,然後建立物件寫入檔案 

void writeobject() throws ioexception
檔案拷貝:找出d盤下test資料夾中所有的 .txt 檔案,拷貝至 e:\test 目錄下,並將所有.txt檔案修改為.bat

public static void movefile(file dir)  else 

}}

I O流 字元流和位元組流

一 位元組流 1 位元組輸出流 outputstream 往指定檔案寫資料 常用方法 close 釋放資源 flush 重新整理流,並強制寫出所有的緩衝的輸出位元組 write byte b 將指定的 byte 陣列寫入到輸出流 write byte b,int off,int len 將指定byt...

io位元組流和字元流

2014 11 30 晚上 位元組流system.in是基本的 inputstream 流,system.out 是基本的 outputstream 流,如果要實現字元流從控制台讀入 bufferedreader bufferedreader new bufferreader reader inpu...

IO流 位元組流和字元流總結

一.位元組流總結 1.位元組輸入流 inputstream fileinputstream 從檔案讀取位元組 bufferedinputstream 加入緩衝功能,提高檔案的讀取效率 bytearrayinputstream 讀取位元組陣列 2.位元組輸出流 outputstream fileout...