Introduction
File I/O (Input/Output) allows reading from and writing to files. Java provides classes in java.io package.
File Class
File class represents file/directory path.
import java.io.*;
public class Main {
public static void main(String[] args) {
File file = new File("test.txt");
System.out.println("Exists: " + file.exists());
System.out.println("Name: " + file.getName());
System.out.println("Path: " + file.getPath());
System.out.println("Size: " + file.length() + " bytes");
System.out.println("Can read: " + file.canRead());
System.out.println("Can write: " + file.canWrite());
System.out.println("Is file: " + file.isFile());
System.out.println("Is directory: " + file.isDirectory());
}
}
Creating File
import java.io.*;
public class Main {
public static void main(String[] args) {
try {
File file = new File("newfile.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());
}
}
}
Writing to File
Using FileWriter:
import java.io.*;
public class Main {
public static void main(String[] args) {
try {
FileWriter writer = new FileWriter("output.txt");
writer.write("Hello World\n");
writer.write("Java File I/O\n");
writer.close();
System.out.println("File written successfully");
} catch (IOException e) {
System.out.println("Error: " + e.getMessage());
}
}
}
Using BufferedWriter:
import java.io.*;
public class Main {
public static void main(String[] args) {
try {
BufferedWriter writer = new BufferedWriter(new FileWriter("output.txt"));
writer.write("Line 1");
writer.newLine();
writer.write("Line 2");
writer.close();
System.out.println("File written");
} catch (IOException e) {
e.printStackTrace();
}
}
}
Reading from File
Using FileReader:
import java.io.*;
public class Main {
public static void main(String[] args) {
try {
FileReader reader = new FileReader("input.txt");
int character;
while ((character = reader.read()) != -1) {
System.out.print((char) character);
}
reader.close();
} catch (IOException e) {
System.out.println("Error: " + e.getMessage());
}
}
}
Using BufferedReader:
import java.io.*;
public class Main {
public static void main(String[] args) {
try {
BufferedReader reader = new BufferedReader(new FileReader("input.txt"));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Append to File
import java.io.*;
public class Main {
public static void main(String[] args) {
try {
// true = append mode
FileWriter writer = new FileWriter("output.txt", true);
writer.write("Appended line\n");
writer.close();
System.out.println("Content appended");
} catch (IOException e) {
e.printStackTrace();
}
}
}
File Operations
Delete File:
import java.io.*;
public class Main {
public static void main(String[] args) {
File file = new File("delete.txt");
if (file.delete()) {
System.out.println("Deleted: " + file.getName());
} else {
System.out.println("Failed to delete");
}
}
}
Rename File:
import java.io.*;
public class Main {
public static void main(String[] args) {
File oldFile = new File("old.txt");
File newFile = new File("new.txt");
if (oldFile.renameTo(newFile)) {
System.out.println("File renamed");
} else {
System.out.println("Failed to rename");
}
}
}
Directory Operations
Create Directory:
import java.io.*;
public class Main {
public static void main(String[] args) {
File dir = new File("mydir");
if (dir.mkdir()) {
System.out.println("Directory created");
} else {
System.out.println("Failed to create directory");
}
}
}
List Files:
import java.io.*;
public class Main {
public static void main(String[] args) {
File dir = new File(".");
String[] files = dir.list();
System.out.println("Files in directory:");
for (String file : files) {
System.out.println(file);
}
}
}
Complete Example: Student Records
import java.io.*;
import java.util.*;
class Student {
int rollNo;
String name;
int marks;
Student(int rollNo, String name, int marks) {
this.rollNo = rollNo;
this.name = name;
this.marks = marks;
}
@Override
public String toString() {
return rollNo + "," + name + "," + marks;
}
}
public class Main {
// Write students to file
static void writeStudents(List<Student> students, String filename) {
try {
BufferedWriter writer = new BufferedWriter(new FileWriter(filename));
for (Student student : students) {
writer.write(student.toString());
writer.newLine();
}
writer.close();
System.out.println("Students written to file");
} catch (IOException e) {
System.out.println("Error writing: " + e.getMessage());
}
}
// Read students from file
static void readStudents(String filename) {
try {
BufferedReader reader = new BufferedReader(new FileReader(filename));
String line;
System.out.println("\nStudents from file:");
while ((line = reader.readLine()) != null) {
String[] parts = line.split(",");
System.out.println("Roll: " + parts[0] + ", Name: " + parts[1] + ", Marks: " + parts[2]);
}
reader.close();
} catch (IOException e) {
System.out.println("Error reading: " + e.getMessage());
}
}
public static void main(String[] args) {
List<Student> students = new ArrayList<>();
students.add(new Student(101, "John", 85));
students.add(new Student(102, "Alice", 92));
students.add(new Student(103, "Bob", 78));
writeStudents(students, "students.txt");
readStudents("students.txt");
}
}
Binary File I/O
Write Binary:
import java.io.*;
public class Main {
public static void main(String[] args) {
try {
DataOutputStream dos = new DataOutputStream(new FileOutputStream("data.bin"));
dos.writeInt(100);
dos.writeDouble(3.14);
dos.writeUTF("Hello");
dos.close();
System.out.println("Binary data written");
} catch (IOException e) {
e.printStackTrace();
}
}
}
Read Binary:
import java.io.*;
public class Main {
public static void main(String[] args) {
try {
DataInputStream dis = new DataInputStream(new FileInputStream("data.bin"));
int num = dis.readInt();
double value = dis.readDouble();
String text = dis.readUTF();
System.out.println("Int: " + num);
System.out.println("Double: " + value);
System.out.println("String: " + text);
dis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
File I/O Classes
| Class | Purpose |
|---|---|
| File | File/directory operations |
| FileReader | Read characters |
| FileWriter | Write characters |
| BufferedReader | Read lines efficiently |
| BufferedWriter | Write lines efficiently |
| FileInputStream | Read bytes |
| FileOutputStream | Write bytes |
| DataInputStream | Read primitive types |
| DataOutputStream | Write primitive types |
Exception Handling
import java.io.*;
public class Main {
public static void main(String[] args) {
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader("file.txt"));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (FileNotFoundException e) {
System.out.println("File not found");
} catch (IOException e) {
System.out.println("Error reading file");
} finally {
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
System.out.println("Error closing file");
}
}
}
}
Best Practices
- Always close streams/readers/writers
- Use BufferedReader/Writer for efficiency
- Handle exceptions properly
- Check file exists before reading
- Use try-with-resources (covered separately)
- Flush before closing writer
- Use absolute paths when needed
Quick Reference
import java.io.*;
// File info
File file = new File("file.txt");
file.exists();
file.length();
file.delete();
// Write to file
FileWriter writer = new FileWriter("file.txt");
writer.write("content");
writer.close();
// Read from file
FileReader reader = new FileReader("file.txt");
int ch;
while ((ch = reader.read()) != -1) {
System.out.print((char) ch);
}
reader.close();
// Read lines
BufferedReader br = new BufferedReader(new FileReader("file.txt"));
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
br.close();
Exam Tips
Remember:
- File class for file operations
- FileReader/Writer for characters
- BufferedReader/Writer for lines
- Always close streams
- IOException must be handled
- FileNotFoundException for missing files
- append mode with true parameter
- read() returns -1 at end
- readLine() returns null at end
- Use finally or try-with-resources
Common Questions:
- What is File I/O?
- File class methods?
- How to read file?
- How to write file?
- BufferedReader vs FileReader?
- How to append to file?
- File operations?
- Directory operations?
- Exception handling in I/O?
- Best practices?