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

时间:2014-03-26 14:22:14

标签: java inputstream

我将从第三方库获取输入流到我的应用程序。 我必须将此输入流写入文件。

以下是我尝试过的代码段:

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

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

3 个答案:

答案 0 :(得分:27)

由于您遇到了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();
}

如果您使用Java 7,解决方案就像下面这样简单:

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

yourInputStream会自动关闭,作为"奖励&#34 ;; Files本身就会处理destination

答案 1 :(得分:2)

如果您不使用Java 7并且无法使用fge的解决方案,您可能希望将OutputStream包装在BufferedOutputStream中

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

这样的缓冲输出流将块中的字节写入文件,这比每字节写入字节更有效。

答案 2 :(得分:1)

使用OutputStreamWriter可以变得更干净:

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

writer.write("data");

writer.close();

您可以在inputStream上使用扫描仪

,而不是编写字符串
Scanner sc = new Scanner(inputStream);
while (sc.HasNext())
    //read using scanner methods