File System and IO

File System and IO

Java offers packages that make working with the file system as easy and painless as possible. These packages enable you to access, manipulate, open, read, write, append, and close files and folders.

Files, just like in real life.
Files, just like in real life.

Opening a File

To open a file, you will need to utilize the File class and specify the name of the file to the constructor. Also, don't forget to import the package:

	
    import java.io.File;

    public class Main {

        public static void main(String[] args) {
            File file = new File("sabe.txt");
        }
    }
	

For the purposes of this tutorial, let's assume the contents of sabe.txt looks like this:

	
    Welcome
    to
    Sabe!
	

After this, you are ready to use your new File object to do numerous different operations.

Reading a File

Now that you have opened a file, you can now read from it. The most common way you'll want to read a file, especially a text file, is line by line. We will need to import the Scanner class that specializes in read text files. This how you do that in Java:

	
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.util.Scanner;

    public class Main {

        public static void main(String[] args) {
            try {
                File file = new File("sabe.txt");
                Scanner reader = new Scanner(file);

                while (reader.hasNextLine()) {
                    String line = reader.nextLine();
                    System.out.println(line);
                }

                reader.close();
            } catch (FileNotFoundException exception) {
                exception.printStackTrace();
            }
        }
    }
	
	
    Welcome
    to
    Sabe!
	

Our reader needs a File instance to initialize itself, so we passed it our previously defined one. Then using a while loop, we keep checking if the text file has another line left, if so, we read it and print it. After that is over, we close our reader. All of this needs to be wrapped in a try-catch block for safety.

Creating a File

You can create a file easily in Java using the createNewFile() method. It will return to you a boolean value indicating whether or not the creation attempt was successful.

	
    import java.io.File;
    import java.io.IOException;

    public class Main {

        public static void main(String[] args) {
            try {
                File file = new File("sabe.txt");
                if (file.createNewFile()) {
                    // file created
                } else {
                    // file already exists
                }
            } catch (IOException exception) {
                exception.printStackTrace();
            }
        }
    }
	

You can also create a new file in an entirely differnt directory by specifing the full path inside your File object, like this if you're on windows.

	
    import java.io.File;
    import java.io.IOException;

    public class Main {

        public static void main(String[] args) {
            try {
                File file = new File("C:\\Users\\sabe\\sabe.txt");
                if (file.createNewFile()) {
                    // file created
                } else {
                    // file already exists
                }
            } catch (IOException exception) {
                exception.printStackTrace();
            }
        }
    }
	

Writing to a File

To write to file, we'll need to use the FileWriter class.

	
    import java.io.FileWriter;
    import java.io.IOException;

    public class Main {

        public static void main(String[] args) {
            try {
                File writer = new FileWriter("sabe.txt");
                writer.write("This is new content!");
                writer.close();
            } catch (IOException exception) {
                exception.printStackTrace();
            }
        }
    }
	

Appending to a File

To append to a file, it's almost identical to when writing to a new file, except we pass an extra parameter to the FileWriter constructor:

	
    import java.io.FileWriter;
    import java.io.IOException;

    public class Main {

        public static void main(String[] args) {
            try {
                File writer = new FileWriter("sabe.txt", true);
                writer.write("This is new content being appended!");
                writer.close();
            } catch (IOException exception) {
                exception.printStackTrace();
            }
        }
    }
	

Renaming a File

To rename a file, just call the renameTo method using two File instances:

	
    import java.io.File;

    public class Main {

        public static void main(String[] args) {
            File from = new File("from.txt");
            File to = new File("to.txt");

            boolean success = from.renameTo(to);
        }
    }
	

It's as simple as that!

Deleting a File

To delete a file, use the delete() method. It will return back a boolean value indicating whether or not the deletion attempt was successful.

	
    import java.io.File;

    public class Main {

        public static void main(String[] args) {
            File file = new File("sabe.txt");
            if (file.delete()) {
                // deleted successfully
            } else {
                // failure to delete
            }
        }
    }
	

Checking if a File exists

Before performing a file operation, you can check if it exists using the exists() method which returns a boolean value indicating whether or not the file exists.

	
    import java.io.File;

    public class Main {

        public static void main(String[] args) {
            File file = new File("sabe.txt");
            boolean exists = file.exists();
        }
    }