9

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 ?

Awesome
  • 5,689
  • 8
  • 33
  • 58

3 Answers3

27

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.

Bass
  • 4,977
  • 2
  • 36
  • 82
fge
  • 119,121
  • 33
  • 254
  • 329
  • Files and Paths is the concept from Java 7. But my application is running with Java 6. Is there any solution like above is available in Java 6. – Awesome Mar 26 '14 at 14:33
  • Aw shucks. OK, then can you use an external library? I was thinking about Guava here – fge Mar 26 '14 at 14:34
  • FYI, the `Files` library is not available in **Android**'s Java 1.7. Got stung by this. http://stackoverflow.com/questions/24869323/android-import-java-nio-file-files-cannot-be-resolved – Joshua Pinter Jan 24 '15 at 22:24
  • the java 7 answer is not correct, with version 18 of guava at least – NimChimpsky Feb 11 '15 at 15:27
  • 1
    @JoshPinter yeah, you have to wonder why. This API is so much better than `File` that there's just no comparison. – fge Feb 11 '15 at 15:28
  • @fge my mistake I though you were using the guava Files api, which doesn't have a method matching the inputs – NimChimpsky Feb 11 '15 at 20:22
2

If you're not on Java 7 and can't use fge's solution, you may want to wrap your OutputStream in a 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.

Melou
  • 874
  • 6
  • 10
1

It can get cleaner with an 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

Scanner sc = new Scanner(inputStream);
while (sc.HasNext())
    //read using scanner methods
Brad Gardner
  • 1,627
  • 14
  • 14
  • 1
    While a `.txt` file was mentioned by the OP, this solution has two major inconvenients: 1. `Scanner` will scrap the delimiter; 2. no encoding specified in the `Writer`. So, you will drop newlines (since this is the default delimiter of `Scanner`) _and_ you risk not using the correct encoding since what you receive are bytes, not chars. More details on this latter problem [here](http://fgaliegue.blogspot.com/2014/03/strings-characters-bytes-and-character.html). – fge Mar 26 '14 at 14:30