java IO 學習(二)
文件表示形式的轉換:
一、從系統文件變成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 學習(二)