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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22663904/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 17:10:16  来源:igfitidea点击:

Efficient way to write InputStream to a File in Java 6

javainputstream

提问by Awesome

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 ?

有没有更好的方法来做到这一点?

采纳答案by fge

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

由于您坚持使用 Java 6,帮自己一个忙并使用 Guava 及其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:

如果您使用 Java 7,解决方案将非常简单:

final Path destination = Paths.get("pathToYourFile");
try (
    final InputStream in = createInputStreamHere();
) {
    Files.copy(in, destination);
}

And yourInputStreamwould have been automatically closed for you as a "bonus"; Fileswould have handled destinationall by itself.

并且yourInputStream会作为“奖金”自动为您关闭;Files本来可以自己处理destination的。

回答by Brad Gardner

It can get cleaner with an OutputStreamWriter:

使用 OutputStreamWriter 可以变得更清晰:

OutputStream outputStream = new FileOutputStream("output.txt");
Writer writer = new OutputStreamWriter(outputStream);

writer.write("data");

writer.close();

Instead of writing a string, you can use a Scanner on your inputStream

您可以在 inputStream 上使用 Scanner,而不是编写字符串

Scanner sc = new Scanner(inputStream);
while (sc.HasNext())
    //read using scanner methods

回答by Melou

If you're not on Java 7 and can't use fge's solution, you may want to wrap your OutputStream in a BufferedOutputStream

如果您不是在 Java 7 上并且不能使用 fge 的解决方案,您可能需要将您的 OutputStream 包装在 BufferedOutputStream 中

BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream("xx.txt"));

Such buffered output stream will write bytes in blocks to the file, which is more efficient than writing byte per byte.

这种缓冲的输出流会将字节以块的形式写入文件,这比逐字节写入更有效。