Java provides the java.io and java.nio packages to work with files. The most commonly used class is File, which allows you to create, read, write, and delete files.
Understanding the File Class
The File class represents file and directory pathnames.
import java.io.File;
public class FileObjectDemo {
public static void main(String[] args) {
File file = new File("data.txt");
System.out.println("File exists? " + file.exists());
}
}
1. Create a File
import java.io.File;
import java.io.IOException;
public class CreateFileDemo {
public static void main(String[] args) {
try {
File file = new File("example.txt");
if (file.createNewFile()) {
System.out.println("File Created: " + file.getName());
} else {
System.out.println("File already exists.");
}
} catch (IOException e) {
System.out.println("Error: " + e.getMessage());
}
}
}
2. Write to a File
You can use FileWriter or BufferedWriter to write text into a file.
import java.io.FileWriter;
import java.io.IOException;
public class WriteFileDemo {
public static void main(String[] args) {
try {
FileWriter writer = new FileWriter("example.txt");
writer.write("Hello from VINAR TECH Java Tutorials!");
writer.close();
System.out.println("Successfully wrote to file.");
} catch (IOException e) {
System.out.println("Error: " + e.getMessage());
}
}
}
3. Append to a File
import java.io.FileWriter;
import java.io.IOException;
public class AppendFileDemo {
public static void main(String[] args) {
try {
FileWriter writer = new FileWriter("example.txt", true); // true = append mode
writer.write("\nAppending new content...");
writer.close();
System.out.println("Content appended.");
} catch (IOException e) {
System.out.println("Error: " + e.getMessage());
}
}
}
4. Read a File
The Scanner class is one of the easiest ways to read text line-by-line.
import java.io.File;
import java.util.Scanner;
public class ReadFileDemo {
public static void main(String[] args) {
try {
File file = new File("example.txt");
Scanner reader = new Scanner(file);
while (reader.hasNextLine()) {
System.out.println(reader.nextLine());
}
reader.close();
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
}
}
5. Delete a File
import java.io.File;
public class DeleteFileDemo {
public static void main(String[] args) {
File file = new File("example.txt");
if (file.delete()) {
System.out.println("File deleted: " + file.getName());
} else {
System.out.println("Unable to delete file.");
}
}
}