File System and IO
Table of Contents
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:
JAVAimport 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:
BASHWelcome
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:
JAVAimport 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();
}
}
}
BASHWelcome
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.
JAVAimport 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 different directory by specifying the full path inside your File
object, like this if you're on windows.
JAVAimport 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.
JAVAimport 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:
JAVAimport 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:
JAVAimport 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.
JAVAimport 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.
JAVAimport java.io.File;
public class Main {
public static void main(String[] args) {
File file = new File("sabe.txt");
boolean exists = file.exists();
}
}
- How to Install Node on Windows, macOS and Linux
- Create an RSS Reader in Node
- How to deploy a .NET app using Docker
- How to deploy a Node app using Docker
- How to Scrape the Web using Node.js and Puppeteer
- Getting User Location using JavaScript's Geolocation API
- Getting Started with Moment.js
- Learn how to build a Slack Bot using Node.js
- Using Push.js to Display Web Browser Notifications
- Building a Real-Time Note-Taking App with Vue and Firebase
- Setting Up a Local Web Server using Node.js
- How To Create a Modal Popup Box with CSS and JavaScript