FileOutputStream in FileInputStream

What is the easiest way to convert FileOutputStream to FileInputStream (part of the code will be large)?

+5
source share
4 answers

This may help you:

http://ostermiller.org/convert_java_outputstream_inputstream.html

This article mentions 3 possibilities:

  • write the full output to the byte array, then read it again
  • use pipes
  • use the cyclic byte buffer (part of the library located on this page).


Just for reference, doing it the other way around: input to output:

A simple solution with Apache Commons IO would be:

IOUtils.copyLarge(InputStream, OutputStream)

or if you just want to copy the file:

FileUtils.copyFile(inFile,outFile);

If you do not want to use Apache Commons IO, here is what the method does copyLarge:

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;
}
+14

FileOutputStream. .

, , OutputStream. , , , FileOutputStream. , . FileOutputStream, , , .

, , File path (a String) FileOutputStream File String FileInputStream.

+4

, ( ), ByteArrayOutputStream ByteArrayInputStream. , ByteArrayOutputStream, ByteArrayInputStream, .

ByteArrayOutputStream outStream = new ByteArrayOutputStream();
// do any output onto outStream you need
ByteArrayInputStream inStream = new ByteArrayInputStream(outStream.toByteArray());
// you can read back the output with inStream now

If you need a buffer (producer / consumer problem), look at the Buffers provided with the java nio package.

+2
source

If you can use the @Thomas example below, otherwise you can do:

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

public class FileInputOutputExample {
  public static void main(String[] args) throws Exception {

    InputStream is = new FileInputStream("in.txt");
    OutputStream os = new FileOutputStream("out.txt");
    int c;
    while ((c = is.read()) != -1) {
      System.out.print((char) c);
      os.write(c);
    }
    is.close();
    os.close();

  }
}

example from java2s.com

EDIT:

As @Thomas deleted his answer, I'll just add Commons IO for reference to handle this:

IOUtils.copy(InputStream is, OutputStream os)
+1
source

All Articles