Java Streams   «Prev  Next»

Lesson 8Using file streams
ObjectiveWrite a program that copies files using file streams.

Using File Streams(Copy files)

Let us look at how you use the FileInputStream and FileOutputStream constructors.

Reading a file

To read a file, just pass the name of the file into the FileInputStream() constructor.
Then use the read() method as normal.
Java looks for files in the current working directory. Generally, this is the directory you are in when you type the name of the Java program to start running the program.

Writing a file

To write data to a file, just pass the name of the file into the FileOutputStream() constructor.
Then use the write() methods as normal. If the file does not exist in the current working directory, it is created. If it does exist, any old data it contains is overwritten.
Instead of overwriting the old data, you can append to the file using the FileOutputStream() constructor and passing in a boolean argument in addition to the name of the file:

public FileOutputStream(String name, boolean append)
 throws IOException

When the append argument is true, data is appended to the file rather than replacing any data that already exists in the file.
Applets are normally not allowed to read or write files. If your applet tries to create a FileInputStream or FileOutputStream, the constructor will throw a SecurityException.

File Streams - Exercise

Click the Exercise link below to write a program that reads two filenames from the command line and copies the first file into the second file.
File Streams - Exercise