Java File Handling
Learn how to handle files in Java. Create, read, write, and delete files using the File class, FileWriter, and Scanner.
File handling is an essential part of any application. In Java, the File class from the java.io package allows us to work with files.
Think of a Filing Cabinet 🗄️.
- You can create new folders (Directories).
- You can create new documents (Files).
- You can write information into them.
- You can read information from them.
1. Creating a File Object
import java.io.File;
File myFile = new File("filename.txt");2. Creating a File
To actually create the file on the disk, use createNewFile().
import java.io.File;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
try {
File myObj = new File("filename.txt");
if (myObj.createNewFile()) {
System.out.println("File created: " + myObj.getName());
} else {
System.out.println("File already exists.");
}
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}3. Writing to a File
Use the FileWriter class.
import java.io.FileWriter;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
try {
FileWriter myWriter = new FileWriter("filename.txt");
myWriter.write("Files in Java might be tricky, but they are fun enough!");
myWriter.close(); // Don't forget to close!
System.out.println("Successfully wrote to the file.");
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}4. Reading a File
Use the Scanner class to read the file contents.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
try {
File myObj = new File("filename.txt");
Scanner myReader = new Scanner(myObj);
while (myReader.hasNextLine()) {
String data = myReader.nextLine();
System.out.println(data);
}
myReader.close();
} catch (FileNotFoundException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}5. Modern File Handling (Java NIO)
The java.nio.file.Files class (introduced in Java 7) offers a more modern and versatile way to handle files.
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.io.IOException;
import java.util.List;
public class NioExample {
public static void main(String[] args) {
Path path = Paths.get("filename.txt");
try {
// Writing to a file
String content = "Hello from Java NIO!";
Files.write(path, content.getBytes());
// Reading from a file
List<String> lines = Files.readAllLines(path);
for (String line : lines) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}Tip 💡: Always close your file writers and readers! If you don't, the file might remain "locked" and other programs (or even your own) won't be able to use it. myWriter.close() is your friend.
Which class is used to write to a file?
Note : Java is a statically-typed language. It means that all variables must be declared before they can be used.
Challenge
Complete this chapter to unlock the next one.
Challenge
Task:
Which method is used to create a new empty file?Key Takeaways
- File Class: Represents a file or directory path.
- Streams: Use
FileWriterfor text,FileOutputStreamfor binary data (images). - Try-with-Resources: Automatically closes files for you.
Common Pitfalls
[!WARNING] Resource Leaks: If you forget to close a file, your OS might lock it, preventing other programs from using it.
Paths: Be careful with absolute paths (e.g.,
C:/Users/...) because they won't work on other computers. Use relative paths.
What's Next?
How do we represent a fixed set of constants, like days of the week? Learn Enums →
