Java File Input and Output
Java Files
File handling is an important part of any
application.
Java has several methods for creating,
reading, updating, and deleting files.
Java File Handling
The File class from the java.io package, allows us to work with files.
To use the File class, create an object of the class, and specify the
filename or directory name:
Example:
import java.io.File; // Import the File class
File myObj = new File("filename.txt"); // Specify the filename
Java File Handling
The File class has many useful methods for
creating and getting information about files.
For example:
Java Create and Write To Files
Create a File
To create a file in Java, you can use the createNewFile() method. This
method returns a boolean value: true if the file was successfully
created, and false if the file already exists. Note that the method is
enclosed in a try...catch block. This is necessary because it throws an
IOException if an error occurs (if the file cannot be created for some
reason):
Java Create and Write To Files
To create a file in a specific directory (requires permission),
specify the path of the file and use double backslashes to
escape the "\" character (for Windows). On Mac and Linux
you can just write the path, like: /Users/name/filename.txt
Example:
File myObj = new File("C:\\Users\\MyName\\filename.txt");
Write To a File
In the following example, we use the FileWriter class together
with its write() method to write some text to the file we created
in the example above. Note that when you are done writing to
the file, you should close it with the close() method:
Java Read Files
Read a File
In the previous chapter, you learned how to create and write to a file.
In the following example, we use the Scanner class to read the contents
of the text file we created in the previous chapter:
Java Delete Files
Delete a File
To delete a file in Java, use the delete()
method:
Delete a Folder
You can also delete a folder. However, it must
be empty: