Java Files
Java File Handling
File handling in Java means working with files to store and access data, such as writing data into a file and reading data from a file.
File handling in Java allows us to create, read, write, update, and delete files stored on the system.
The File class from the java.io package is used to work with files. To use the File class, we create an object of the class and specify the file name or directory name.
File handling in Java is the process of managing files to store, read, write, update, and delete data using Java programs.
Create Files
Creating a file in Java means making a new file in the system using a Java program so that data can be stored in it.
Java provides the File class from the java.io package to create and manage files. Creating a file in Java means generating a new file using Java code where we can store data.
In Java, you can create a file using the createNewFile() method from the File class.
This method returns:
- true → if the file is created successfully
- false → if the file already exists
It is used inside a try...catch block because it may throw an IOException if an error occurs while creating the file.
Example
import java.io.File; // Import File class from java.io package
import java.io.IOException; // Import IOException class for handling errors
public class CreateFile {
public static void main(String[] args) {
try {
// Create a File object and specify the file name
File myObj = new File("filename.txt");
// createNewFile() method creates a new file
// It returns true if file is created successfully
// It returns false if file already exists
if (myObj.createNewFile()) {
// If file is created successfully
System.out.println("File created: " + myObj.getName());
} else {
// If file already exists
System.out.println("File already exists.");
}
} catch (IOException e) {
// If any error occurs during file creation
System.out.println("An error occurred.");
// Prints detailed error message
e.printStackTrace();
}
}
}
Write To a File
Writing to a file in Java means saving information (like text) into a file on your computer using a program.
If you are just starting with Java, the easiest way to do this is by using something called FileWriter. It helps you create a file and put text inside it.
- The write() method is used to add text into the file
- The close() method is used to finish the work and save the file properly
There are also other ways to write files in Java. Each method is useful for different situations, like:
- writing simple text
- writing large amounts of data
- writing formatted or structured content
Example
import java.io.FileWriter; // Import class to write data into a file
import java.io.IOException; // Import class to handle errors
public class WriteToFile {
public static void main(String[] args) {
try {
// Create a FileWriter object to write to "filename.txt"
FileWriter myWriter = new FileWriter("filename.txt");
// Write text into the file
myWriter.write("Files in Java might be tricky, but it is fun enough!");
// Close the writer to save the file properly
myWriter.close();
// Print message if writing is successful
System.out.println("Successfully wrote to the file.");
} catch (IOException e) {
// This block runs if an error occurs
System.out.println("An error occurred.");
// Print error details
e.printStackTrace();
}
}
}
Read Files
Reading a file in Java means getting or opening data from a file using a Java program so you can see or use that data.
Example
import java.io.File; // Import File class (to open a file)
import java.io.FileNotFoundException; // Import exception class for file errors
import java.util.Scanner; // Import Scanner class (to read data)
public class ReadFile {
public static void main(String[] args) {
// Create a File object and specify the file name
File myObj = new File("filename.txt");
// try-with-resources: Scanner will close automatically after use
try (Scanner myReader = new Scanner(myObj)) {
// Check if the file has more lines
while (myReader.hasNextLine()) {
// Read one line from the file
String data = myReader.nextLine();
// Print the line on the screen
System.out.println(data);
}
} catch (FileNotFoundException e) {
// This block runs if file is not found
System.out.println("An error occurred.");
// Print full error details
e.printStackTrace();
}
}
}
Delete Files
Deleting a file in Java means removing a file from your computer using a Java program so it no longer exists. This is done using the delete() method, which helps to erase the file permanently.
Example
import java.io.File; // Import File class to handle file operations
public class DeleteFile {
public static void main(String[] args) {
// Create a File object that represents the file to be deleted
File myObj = new File("filename.txt");
// Check if the file is deleted successfully
if (myObj.delete()) {
// If deletion is successful, print file name
System.out.println("Deleted the file: " + myObj.getName());
} else {
// If deletion fails, print error message
System.out.println("Failed to delete the file.");
}
}
}