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
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
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.
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.