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.
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:
For the purposes of this tutorial, let's assume the contents of sabe.txt looks like this:
BASH
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:
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.
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.