Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FileOutputStream into FileInputStream

Tags:

java

file-io

What is the simplest way to convert a FileOutputStream into FileInputStream (a piece of code would be great)?

like image 616
Pen Avatar asked Sep 30 '11 13:09

Pen


2 Answers

This might help you:

http://ostermiller.org/convert_java_outputstream_inputstream.html

This article mentions 3 possibilities:

  • write the complete output into a byte array then read it again
  • use pipes
  • use a circular byte buffer (part of a library hosted on that page)


Just for reference, doing it the other way round (input to output):

A simple solution with Apache Commons IO would be:

IOUtils.copyLarge(InputStream, OutputStream)

or if you just want to copy a file:

FileUtils.copyFile(inFile,outFile);

If you don't want to use Apache Commons IO, here's what the copyLarge method does:

public static long copyLarge(InputStream input, OutputStream output) throws IOException 
{
  byte[] buffer = new byte[4096];
  long count = 0L;
  int n = 0;
  while (-1 != (n = input.read(buffer))) {
   output.write(buffer, 0, n);
   count += n;
  }
  return count;
}
like image 106
Thomas Avatar answered Sep 22 '22 06:09

Thomas


I receive an FileOutputStream. What I want is read it.

You certainly can't read from an OutputStream. I think you mean you want to read from the file being written to by the FileOutputStream. I don't think you can do that either. The FileOutputStream doesn't seem to keep a reference to the file being written to.

What you need to do is discover what File or path (a String) was passed into the FileOutputStream and use that same File or String to create a new FileInputStream.

like image 21
Mark Peters Avatar answered Sep 19 '22 06:09

Mark Peters