Java Reference
In-Depth Information
Copying the Contents of a File
After you learn about input and output streams, it is simple to write code that copies the contents of a file to another
file. You need to use the byte-based input and output streams ( InputStream and OutputStream objects) so that your
file copy program will work on all kinds of files. The main logic in copying a file is to keep reading from the input
stream until the end of file and keep writing to the output stream as data is read from the input stream. The following
snippet of code shows this file-copy logic:
// Copy the contents of a file
int count = -1;
byte[] buffer = new byte[1024];
while ((count = in.read(buffer)) != -1) {
out.write(buffer, 0, count);
}
the file-copy logic copies only the file's contents. You will have to write logic to copy file's attributes. the nIO
2.0 apI, covered in Chapter 10, provides a copy() method in the java.nio.file.Files class to copy the contents and
attributes of a file to another file. please use the Files.copy() method to copy a file.
Tip
Standard Input/Output/Error Streams
A standard input device is a device defined and controlled by the operating system from where your Java program
may receive the input. Similarly, the standard output and error are other operating system-defined (and controlled)
devices where your program can send an output. Typically, a keyboard is a standard input device, and a console acts
as a standard output and a standard error device. Figure 7-10 depicts the interaction between the standard input,
output, and error devices, and a Java program.
Standard Output
Device
Standard Input
device
Java Program
Standard Error
Device
Figure 7-10. Interaction between a Java program and standard input, output, and error devices
What happens when you use the following statement to print a message?
System.out.println("This message goes to the standard output device!");
Typically, your message is printed on the console. In this case, the console is the standard output device and the
Java program lets you send some data to the standard output device using a high level println() method call. You
saw a similar kind of println() method call in the previous section when you used the PrintStream class that is a
concrete decorator class in the OutputStream class family. Java makes interacting with a standard output device on
a computer easier. It creates an object of the PrintStream class and gives you access to it through a public static
variable out in the System class. Look at the code for the System class; it declares three public static variables (one
for each device: standard input, output, and error) as follows:
 
 
Search WWH ::




Custom Search