標籤:輸入資料流 並且 puts buffer 檔案的 gpo 輸出 write reader
檔案表示形式的轉換:
一、從系統檔案變成java中可以使用的檔案對象
File file = new FIle("檔案的路徑");
二、讀取檔案系統中檔案的原始位元組流,要讀取字元流,請考慮使用 FileReader (File 轉 InputStream)
FileInputStream fis = new FileInputStream(file);
三、建立一個檔案輸出資料流,用於寫入原始位元組流
FileOutputStream fos = new FileOutputStream(file);
四、將一個輸入資料流其中的資料寫入到一個byte數組中(InputStream 轉 byte[])
方法一:
FileInputStream fis = new FileInputStream(file);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buff = new byte[100]; //buff用於存放迴圈讀取的臨時資料
int rc = 0;
while ((rc = fis.read(buff, 0, 100)) > 0) {
baos.write(buff, 0, rc);
}
byte[] in_b = baos.toByteArray(); // in_b為轉換之後的結果
方法二:
FileInputStream fis = new FileInputStream(file);
byte[] buff = new byte[fis.available()];
fis.read(buff);// read方法返回一個int值,並且把fis讀取到的資料儲存到buff數組中
五、byte[]轉換成InputStream
ByteArrayInputStream bais = new ByteArrayInputStream(byte[] buf);
六、根據byte數組,組建檔案
File file = new File(""); // 建立一個File
OutputStream output = new FileOutputStream(file);// 轉成OutputStream 形式
BufferedOutputStream bufferedOutput = new BufferedOutputStream(output);// 轉成BufferedOutputStream
bufferedOutput.write(byt);// 把byte[]寫入BufferedOutputStream
注意有些語句可能會拋出異常,注意流要記得關閉
java IO 學習(二)