java存入文件6,在Java 6中将InputStream写入文件的有效方法

I will get input stream from third party library to my application.

I have to write this input stream to a file.

Following is the code snippet I tried:

private void writeDataToFile(Stub stub) {

OutputStream os = null;

InputStream inputStream = null;

try {

inputStream = stub.getStream();

os = new FileOutputStream("test.txt");

int read = 0;

byte[] bytes = new byte[1024];

while ((read = inputStream.read(bytes)) != -1) {

os.write(bytes, 0, read);

}

} catch (Exception e) {

log("Error while fetching data", e);

} finally {

if(inputStream != null) {

try {

inputStream.close();

} catch (IOException e) {

log("Error while closing input stream", e);

}

}

if(os != null) {

try {

os.close();

} catch (IOException e) {

log("Error while closing output stream", e);

}

}

}

}

Is there any better approach to do this ?

解决方案

Since you are stuck with Java 6, do yourself a favour and use Guava and its Closer:

final Closer closer = Closer.create();

final InputStream in;

final OutputStream out;

final byte[] buf = new byte[32768]; // 32k

int bytesRead;

try {

in = closer.register(createInputStreamHere());

out = closer.register(new FileOutputStream(...));

while ((bytesRead = in.read(buf)) != -1)

out.write(buf, 0, bytesRead);

out.flush();

} finally {

closer.close();

}

Had you used Java 7, the solution would have been as simple as:

final Path destination = Paths.get("pathToYourFile");

try (

final InputStream in = createInputStreamHere();

) {

Files.copy(in, destination);

}

And yourInputStream would have been automatically closed for you as a "bonus"; Files would have handled destination all by itself.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值