1. 程式人生 > >Java IO流 寫入資料到檔案中學習總結

Java IO流 寫入資料到檔案中學習總結

這裡就不介紹InputStream、OutputStream、FileInputStream、 FileOutputStream了,這裡主要說明的是IO對檔案的操作。

 

將資料寫到檔案中,平常,我們會通過下面程式碼進行對檔案的寫操作。

InputStream inputStream = new FileInputStream(new File("e://1.png"));
OutputStream outputStream1 = new FileOutputStream(new File("e:\\12.png"));
int bufferReader;
byte[] buffer = new byte[100];
while((bufferReader = inputStream.read(buffer,0,100)) != -1){
     outputStream1.write(buffer);
}
outputStream1.flush();
outputStream1.close();

將字串寫入到檔案中,平常我們操作如下:

//將字串轉換為byte[],然後寫入到ByteArrayInputStream中,
//然後再讀取寫入到FileOutputStream,然後轉存到file中
InputStream stream = new ByteArrayInputStream("this is the test message!!!".getBytes());
File file = File.createTempFile("test3", ".bpmn20.xml");
OutputStream os = new FileOutputStream(file);

int bytesRead = 0;                     //此處可以使用FileUtils.copyInputStreamToFile(inputStream,file);
byte[] buffer = new byte[8192];
while ((bytesRead = stream.read(buffer, 0, 8192)) != -1) {
  os.write(buffer, 0, bytesRead);
}
os.close();
stream.close()

我們會通過buffer,經資料一點一點底寫到OutputStream,再通過 FileOutputStream寫到File中,這樣操作固然沒錯,但程式碼量太大,我們可以使用已經封裝好的方法進行檔案的寫操作。

 

一.通過FileUtils進行檔案的寫操作

<dependency>
	<groupId>commons-io</groupId>
	<artifactId>commons-io</artifactId>
	<version>2.2</version>
</dependency>
InputStream inputStream = new FileInputStream(new File("e://1.png"));
File file = new File("e:\\12.png");
FileUtils.copyInputStreamToFile(inputStream,file);

二.如果檔案是圖片,可以通過ImageIO操作

InputStream inputStream = new FileInputStream(new File("e://1.png"));
BufferedImage image  = ImageIO.read(inputStream);
ImageIO.write(image, "png", outputStream1);
outputStream1.flush();
outputStream1.close();


三.通過FileUtils將字串寫入到檔案

FileUtils.writeByteArrayToFile(new File("e:\\q.txt"),"this is the test message!!!".getBytes());