How to Copy Input Output Streams in Java
The Java programming language handles data by implementing a "stream." Streams are programming constructs that greatly simplify data manipulation. Streams have an undetermined length and new data is stored in a buffer. When the buffer fills, the stream is flushed and data is then processed. You can copy an input stream to an output stream using some Java library functions. This may come in handy if you are programming an application that is heavy in the data processing department.
Things You'll Need
- Java software development kit with NetBeans integrated development
- Environment (IDE) bundle
Instructions
-
-
1
Load the NetBeans IDE by clicking on its program icon. When the program loads, navigate to "New/New Project" and select "Java Desktop Application" from the list on the right side of the screen. A new project is created, and a blank desktop application window appears in the main workspace.
-
2
Import the stream libraries, which require the Exception library. To import these libraries, write the following code at the top of your source code file:
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
-
-
3
Create an exception "Try/Catch" block by writing the following within the curly brackets of the main function:
try {}
catch(Exception e) {}
-
4
Declare an input and output stream by writing the following within the curly brackets of the try block:
in = new FileInputStream("Input Text");
out = new FileOutputStream("Output");
-
5
Create a temporary integer data type that will act as an intermediary between the input and output streams. Write the next line of code beneath the ones written in the previous step:
int tmp;
-
6
Loop through the input stream using a while loop by writing the next line of code beneath the line written in the previous step:
while ((tmp = in.read()) != -1) {}
-
7
Copy the data from the input stream to the output stream by placing the next line of code between the curly brackets of the while loop.
out.write(tmp);
-
8
Execute the program by pressing "F6." The input stream "Input Text" is copied to the output stream, overwriting the text "Output."
-
1