在Java 6中将InputStream写入文件的有效方法 [英] Efficient way to write InputStream to a File in Java 6

查看:790
本文介绍了在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 ?

推荐答案

既然你坚持使用Java 6,请帮自己一个忙,并使用Guava及其 更接近

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();
}






您是否使用过Java 7 ,解决方案就是这样简单:


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);
}

yourInputStream 会已作为奖金自动关闭; 文件本身会处理目的地

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

这篇关于在Java 6中将InputStream写入文件的有效方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆