简体   繁体   English

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

[英]Efficient way to write InputStream to a File in Java 6

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 : 既然你坚持使用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 yourInputStream would have been automatically closed for you as a "bonus"; 并且yourInputStream会自动关闭为“奖励”; Files would have handled destination all by itself. Files本身就可以处理destination

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. 这样的缓冲输出流将块中的字节写入文件,这比每字节写入字节更有效。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Java InputStream。 有正确有效的方法吗? - Java InputStream . Is there is Correct And Efficient way? Java:从inputStream读取和写入outputStream的最有效方法(加上一些修改) - Java: Most efficient way to read from inputStream and write to an outputStream (plus a few modifications) 将 Java InputStream 的内容写入 OutputStream 的简单方法 - Easy way to write contents of a Java InputStream to an OutputStream Java输入流/输出流以相同名称写入文件 - Java inputstream/outputstream write to file with same name 用Java编写大型文本文件的最有效方法是什么? - What's the most efficient way to write large text file in java? Android-读取输入流并将其另存为文件的最有效方法是什么? - Android - Whats the most efficient way to read an inputstream and save as file? 写入文件最有效的方法? - Most efficient way to write to a file? 读取InputStream并写入文件 - Read InputStream and Write to a File 是否有一种很好的,安全的,快速的方法将InputStream写入Scala中的文件? - Is there a nice, safe, quick way to write an InputStream to a File in Scala? Java:使用ArrayList编写pojo的最有效方法 - Java: The most efficient way to write pojo with ArrayList
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM