Working with Files

The class is used to obtain file properties and to delete and rename files. Essentially, it is a wrapper class for the file name and its directory path, intended to provide a level of abstraction to deal with most of the machine-dependent complexities of files and path names in a machine-independent fashion.

It is perhaps counter-intuitive, but the File class is NOT for reading and writing file contents -- it contains no methods for doing so. Instead file I/O (i.e., input/output) can be accomplished via the Scanner and PrintWriter classes.

Importantly, you should make sure to close any Scanner or PrintWriter variables when you are done with them, by calling their close() methods.

The following shows some examples of using these three classes together to create, write to, and read from a file.

import java.util.Scanner;

public class FileFun {

    public static void main(String[] args) throws FileNotFoundException {
        File myFile = new File("/Users/pauloser/Desktop/myfile.txt");
        // If working on a windows computer, change the above line to the following:
        // File f = new File("C:\\Users\\oser\\Desktop\\myfile.txt");
        // Create the text file described above if it doesn't yet exist, and then
        // write two lines of text out to this text file
        PrintWriter printWriter = new PrintWriter(myFile);
        printWriter.println("The first line of text in myfile.txt");
        printWriter.println("Another line of text in the same file");
        printWriter.close();  //<-- Don't forget to close the printWriter 
                              //    when you are done writing with it!
        // Read two lines of text in from the text file specified above
        Scanner fileScanner = new Scanner(myFile);
        String firstLine = fileScanner.nextLine();
        String secondLine = fileScanner.nextLine();
        System.out.println("1: " + firstLine);
        System.out.println("2: " + secondLine);
        fileScanner.close();  //<-- Don't forget to close the scanner 
                              //    when you are done reading with it!

The result of running the above code will be the creation of a file named "myfile.txt" on the desktop, and the following is printed to the console:

1: The first line of text in myfile.txt
2: Another line of text in the same file