File Operations in Java
File operations include creating, reading, updating, and deleting data stored for different purposes.
Introduction
In a typical traditional office setting, files are used to store crucial data that are later referenced for decision-making. File use also extends to the organization of crucial information including images, and texts that provide data essential in informing decisions. File operations include creating, reading, editing, and deleting data stored for different purposes. In the case of a computer system, file operations encompass the creation of files, writing into files, deletion of files, and file reading. In programming, file management is essential in the development of large-scale systems that rely on files for different processes. In this article, we will look into different file operations in Java, ensuring we can use files appropriately.
Creating a File
File creation is an important process that allows the user to utilize the file for a write operation at a later stage. During file creation, we use the class provided by java.io.File and the createNewFile() method that returns a boolean. If the file is created it returns true. It returns a false if the file has already been created.
package FileOperations;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class WriteFile {
public static void main(String[] args) {
try {
FileWriter myFileObject = new FileWriter("filename.txt");
myFileObject.write("File operations!");
myFileObject.close();
} catch(IOException e) {
System.out.println("An error occurred!");
}
}
}
In the above code block, we enclose our code in the try… catch block to take care of a possible IOException that occurs when file creation fails.
We then create a file object named myFile and assign the value to a new File called filename with the extension .txt. In the if...else statement, we call createNewFile() on myFile object. If a success we alert the user we have successfully created the file filename.txt. Otherwise, we alert the user that the file already exists. Notably, running the above program twice will provide the following outcomes;
//Created a new file filename.txt
//File filename.txt exists already
In the first run, the file will be created, and in the proceeding runs the file already exists, as such will not be created, and instead, the else statement is executed.
Try Kodaschool for free
Click below to sign up and get access to free web, android and iOs challenges.
Write into File
Writing into a file is made possible in Java by the java.io.FileWriter class. Before writing into a file, we create a FileWriter object that takes the argument of the file (filename and extension) in which we want to write. Similar to how we handled IOException we use the try-catch statement to prevent a crash.
package FileOperations;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class WriteFile {
public static void main(String[] args) {
try {
FileWriter myFileObject = new FileWriter("filename.txt");
myFileObject.write("File operations!");
myFileObject.close();
} catch(IOException e) {
System.out.println("An error occurred!");
}
}
}
In the above code block, we initialize the FileWriter object called myFileObject with the file we will be writing on; filename.txt. To write into the file, we use the write() method which accepts the content we are attempting to write into the file. We then close the file using the close() method ending the write operation.
Read File Content
In the previous section, we performed a write operation into the file filename.txt. In this section, we are going to read the file content. To read file content, we use the java.util.Scanner class, alongside the hasNextLine() method which checks whether there exist more lines of text on the file. We wrap our code in a try-catch block when reading file content. We execute the read operation in the try statement and use the catch block to handle the FileNotFoundException.
package FileOperations;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ReadFile {
public static void main(String[] args) {
try {
File myFileObject = new File("filename.txt");
Scanner myReader = new Scanner(myFileObject);
while(myReader.hasNextLine()) {
String data = myReader.nextLine();
System.out.println(data);
}
myReader.close();
} catch(FileNotFoundException e) {
System.out.println("An error occurred!");
e.printStackTrace();
}
}
}
In the above code snippet, we first create a File object to initialize the file whose content we will be reading. We then create a Scanner object that we will use to read the content of our File Object. To read the contents of our file, we use a while loop that checks whether the file has more lines to read, and stops when there is no more content left when we use the close() method. Inside the while loop, we use the Scanner object and the nextLine() method to read our file content and store it in the String variable data. We then display our data.
Delete File
The last file operation is deletion. While not quite the best approach when handling files, deletion is still a fundamental action in file operations. To delete a file, we use the delete() method.
package FileOperations;
import java.io.File;
public class DeleteFile {
public static void main(String[] args) {
File myFile = new File("filename.txt");
if(myFile.exists()) {
if(myFile.delete()) {
System.out.println("File " + myFile + " deleted!");
} else {
System.out.println("Delete " + myFile + " failed!");
}
} else {
System.out.println("File "+ myFile + " does not exist!");
}
}
}
It is always a good practice to check if a file exists before proceeding to delete the file.
Note: It is important to always handle your exceptions when you work with files.