122k views
3 votes
Using Byte Streams

We'll explore FileInputStream and FileOutputStream by
examining an example program named CopyBytes, which uses
byte streams to copy first.txt, one byte at a time.
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class CopyBytes {
public static void main(String[] args) throws IOException {
FileInputStream in = null;
FileOutputStream out = null;
try {
in = new FileInputStream("first.txt");
out = new FileOutputStream("second.txt");
int c;
while ((c = in.read()) != -1) {
out.write(c):
}
} finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();

User TitusAdam
by
7.9k points

1 Answer

2 votes

Final answer:

The example program demonstrates the use of byte streams in Java to copy the contents of one file to another file one byte at a time using FileInputStream and FileOutputStream.

Step-by-step explanation:

The subject of this question is Computers and Technology. The example program provided, named CopyBytes, demonstrates the use of byte streams in Java to copy the contents of one file to another file, one byte at a time.

The program starts by creating an instance of FileInputStream to read the bytes from the source file, and an instance of FileOutputStream to write the bytes to the destination file.

The while loop reads the bytes from the input stream using the read() method and writes them to the output stream using the write() method, until the end of the input stream is reached. Finally, the program closes the input and output streams using the close() method.

User Sharanya Dutta
by
8.1k points