Java IO流 写入数据到文件中学习总结

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zc_ad/article/details/85251845

这里就不介绍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());

猜你喜欢

转载自blog.csdn.net/zc_ad/article/details/85251845
今日推荐