Efficient way to write InputStream to a File in Java 6

后端 未结 3 684
忘掉有多难
忘掉有多难 2021-02-15 02:52

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:

p         


        
3条回答
  •  离开以前
    2021-02-15 03:14

    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.

提交回复
热议问题