Java Lab Manual – File Handling Programs
This lab manual presents basic file handling exercises in Java to help students understand
how to read from, write to, and manipulate text files using core Java I/O classes.
🔹 Program 1: Read and Write using FileReader & FileWriter
Objective: To read text from one file and write it to another using FileReader and
FileWriter.
import java.io.*;
public class FileCopyBasic {
public static void main(String[] args) throws IOException {
FileReader fr = new FileReader("input.txt");
FileWriter fw = new FileWriter("output.txt");
int c;
while ((c = fr.read()) != -1) {
fw.write(c);
}
fr.close();
fw.close();
System.out.println("File copied successfully.");
}
}
🔹 Program 2: BufferedReader & BufferedWriter
Objective: Use buffered streams to efficiently read and write text files.
import java.io.*;
public class BufferedFileCopy {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new
FileReader("input.txt"));
BufferedWriter bw = new BufferedWriter(new
FileWriter("buffered_output.txt"));
String line;
while ((line = br.readLine()) != null) {
bw.write(line);
bw.newLine();
}
br.close();
bw.close();
System.out.println("Buffered file copy completed.");
}
}
🔹 Program 3: Count Lines, Words, and Characters
Objective: Analyze file content to count lines, words, and characters.
import java.io.*;
public class FileStats {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new
FileReader("input.txt"));
int lines = 0, words = 0, chars = 0;
String line;
while ((line = br.readLine()) != null) {
lines++;
chars += line.length();
words += line.split("\\s+").length;
}
br.close();
System.out.println("Lines: " + lines);
System.out.println("Words: " + words);
System.out.println("Characters: " + chars);
}
}
🔹 Program 4: Copy File using Streams
Objective: Copy content from one file to another using byte streams.
import java.io.*;
public class FileStreamCopy {
public static void main(String[] args) throws IOException {
FileInputStream in = new FileInputStream("source.txt");
FileOutputStream out = new FileOutputStream("destination.txt");
int byteData;
while ((byteData = in.read()) != -1) {
out.write(byteData);
}
in.close();
out.close();
System.out.println("Stream copy completed.");
}
}
✅ Conclusion:
These programs form the foundation of file handling in Java and are essential for projects
involving file-based data processing. Mastery of these will enable efficient file
manipulation in real-world applications.