Easy way to write contents of a Java InputStream to an OutputStream
Java 9
Since Java 9, InputStream
provides a method called transferTo
with the following signature:
public long transferTo(OutputStream out) throws IOException
As the documentation states, transferTo
will:
Reads all bytes from this input stream and writes the bytes to the
given output stream in the order that they are read. On return, this
input stream will be at end of stream. This method does not close
either stream.This method may block indefinitely reading from the
input stream, or writing to the output stream. The behavior for the
case where the input and/or output stream is asynchronously closed, or
the thread interrupted during the transfer, is highly input and output
stream specific, and therefore not specified
So in order to write contents of a Java InputStream
to an OutputStream
, you can write:
input.transferTo(output);
Best way to Pipe InputStream to OutputStream
I would say a fixed buffer size is the best/easiest to understand. However there are a few problems.
You're writing the entire buffer to the output stream each time. For the final block the read may have read < 1024 bytes so you need to take this into account when doing the write (basically only write number of bytes returned by
read()
In the dynamic buffer case you use
available()
. This is not a terribly reliable API call. I'm not sure in this case inside a loop whether it will be ok, but I wouldn't be suprised if it was implemented sub-optimally in some implementations of InputStream.The last case you are casting to
FileInputStream
. If you intend for this to be general purpose then you can't use this approach.
Using inputStream and OutputStream to read and write data to a process
This should work:
public static void main(String[] args) throws IOException {
String command[] = {"java.exe", "-cp", "C:\\Users\\Mahika\\Documents\\NetBeansProjects\\JavaTest\\compilerTest", "InputInteger"};
ProcessBuilder pb = new ProcessBuilder(command);
Process p = pb.start();
System.out.println("Process started");
BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
System.out.println(br.readLine());
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
PrintStream ps = new PrintStream(p.getOutputStream(), true);
ps.println(i);
System.out.println(br.readLine());
}
Just make sure that input prompt in InputInteger
class is finished by a newline character (e.g. created by println
and not print
).
Java inputstream/outputstream write to file with same name
If you'd prefer not to use the popular temporary-file approach, then you can always just read in the whole file, then write back to it afterwards.
Here's a straight-forward implementation.
public static void addRootTag(File xml) throws IOException {
final List<String> lines = new ArrayList<>();;
try (Scanner in = new Scanner(xml)) {
while (in.hasNextLine())
lines.add(in.nextLine());
}
try (PrintStream out = new PrintStream(xml)) {
out.println("<root>");
for (String line : lines) {
// indentation, if you want
out.print(" ");
out.println(line);
}
out.println("</root>");
}
}
Write from one OutputStream to another InputStream
Yes it is! PipedOutputStream
(see) and a PipedInputStream
(see) is what you need.
Here is a little example how to use it:
public static void main(String[] args) throws ParseException, IOException {
PipedInputStream inputStream = new PipedInputStream();
PipedOutputStream outputStream = new PipedOutputStream(inputStream);
// Write some data to the output stream
writeDataToOutputStream(outputStream);
// Now read that data
Scanner src = new Scanner(inputStream);
System.out.println(src.nextLine());
}
private static void writeDataToOutputStream(OutputStream outputStream) throws IOException {
outputStream.write("Hello!\n".getBytes());
}
The code will output:
Hello!
Outputstream start writing when inputstream starts reading
You could use a StreamingOutput
and use your CustomSerializer
to write to the provided OutputStream
StreamingOutput entity = new StreamingOutput() {
@Override
public void write(OutputStream out)
throws IOException, WebApplicationException {
CustomSerializer.serialize(bigObject, out);
}
};
The write()
method will be called by Jersey, giving you a chance to write directly to response entity stream.
Then just use a FormDataBodyPart
BodyPart bigPart = new FormDataBodyPart(
"data", entity, MediaType.APPLICATION_OCTET_STREAM_TYPE);
MultiPart multiPart = new FormDataMultiPart().bodyPart(bigPart);
Related Topics
Accept Server'S Self-Signed Ssl Certificate in Java Client
Difference Between a Static and a Non-Static Initialization Code Block
Netbeans Gui Editor Generating Its Own Incomprehensible Code
How to Format the Day of the Month to Say "11Th", "21St" or "23Rd" (Ordinal Indicator)
How to Convert Java.Util.Date to Java.Sql.Date
Instantiating a Generic Class in Java
Creating an Instance Using the Class Name and Calling Constructor
How to Do Url Decoding in Java
How to Pass a Function as a Parameter in Java
How to Use a Servlet Filter in Java to Change an Incoming Servlet Request Url
Why Are Arrays Covariant But Generics Are Invariant
Initialization of an Arraylist in One Line
Overloaded Method Selection Based on the Parameter'S Real Type
Best Way to Format a Double Value to 2 Decimal Places