A stream is a device for transmitting or retrieving 8-bit or byte values. A file is a collection of items stored on an external device. The Java object FileStream provides the means to access the data values but does not actually hold the file contents.
There are two independent and largely parallel systems involved in I/O. InputStream and OutputStream are used to read and write 8-bit quantities and process binary files. The alternative hierarchy has two different classes Reader and Writer that are used to read and write 16-bit Unicode character values and process text files.
The File class provides methods for dealing with files or directories. File systems are organized into a hierarchy. A path is a description of a file's location in the hierarchy. When a program is running, the program' directory is considered the current directory. Any files located in the current directory can be referred to by name alone. The relative path is the location of a file with respect to the current directory. The absolute path starts at the root directory.
public class File extends Object implements Serializable { // Constructors public File ( String path ); public File ( String path, String name ); // Public methods public boolean canRead(); // is the file readable? public boolean canWrite(); // is the file writeable? public boolean delete(); // delete the file public boolean exists(); // does the file exist public long lastModified(); // when was the file last modified public long length(); // How many bytes does it contain public boolean renameTo(File f); // rename this file to f's name }
File inFile = new File ( "FileIO.txt" );
A text file can be read using a Scanner object. Using the Scanner offers the advantage of using the methods that come with the Scanner class.
import java.util.Scanner; import java.io.*; public class ReadTextFile { public static void main (String [] args) throws IOException { File inFile = new File ("input.txt"); Scanner sc = new Scanner (inFile); while (sc.hasNextLine()) { String line = sc.nextLine(); System.out.println (line); } sc.close(); } }
To write text to a file you open an output stream by using the class FileWriter. If the file does not exist a new empty file with this name is created. If the file already exists opening it erases the data in the file. If you want to append to the file use the following option when creating the FileWriter object:
FileWriter fWriter = new FileWriter (outFile, true);
The class PrintWriter has methods print(), printf() and println() that will allow us to write to a file.
import java.io.*; public class WriteTextFile { public static void main (String [] args) throws IOException { File outFile = new File ("output.txt"); FileWriter fWriter = new FileWriter (outFile); PrintWriter pWriter = new PrintWriter (fWriter); pWriter.println ("This is a line."); pWriter.println ("This is another line."); pWriter.close(); } }