1. Overview of Java File I/O
Java provides several ways to read from and write to files:
Legacy I/O (java.io package) – FileReader, FileWriter, BufferedReader, BufferedWriter
New I/O (java.nio package) – Files, Paths, ByteBuffer
Streams – InputStream, OutputStream for binary data
Key concepts:
Text files → handled as characters
Binary files → handled as bytes
2. Reading Files
A. Using BufferedReader (Text File)
import java.io.*;
public class ReadFileExample {
public static void main(String[] args) {
String fileName = "example.txt";
try (BufferedReader br = new BufferedReader(new FileReader(fileName))) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Notes:
BufferedReader reads lines efficiently.
try-with-resources automatically closes the file.
B. Using Files.lines (Java NIO)
import java.nio.file.*;
import java.io.IOException;
public class ReadFileNIO {
public static void main(String[] args) {
Path path = Paths.get("example.txt");
try {
Files.lines(path).forEach(System.out::println);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Notes:
Requires Java 8+
Stream API makes it concise and functional
C. Reading Binary Files
import java.io.*;
public class ReadBinaryFile {
public static void main(String[] args) {
try (FileInputStream fis = new FileInputStream("image.png")) {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = fis.read(buffer)) != -1) {
// process bytes
System.out.println("Read " + bytesRead + " bytes");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Notes:
InputStream is used for bytes (binary files)
Always handle exceptions
3. Writing Files
A. Using BufferedWriter
import java.io.*;
public class WriteFileExample {
public static void main(String[] args) {
String fileName = "output.txt";
try (BufferedWriter bw = new BufferedWriter(new FileWriter(fileName))) {
bw.write("Hello, World!");
bw.newLine();
bw.write("Writing another line.");
} catch (IOException e) {
e.printStackTrace();
}
}
}
Notes:
newLine() writes platform-specific line separator
FileWriter overwrites by default; use FileWriter(fileName, true) to append
B. Using Files.write (Java NIO)
import java.nio.file.*;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
public class WriteFileNIO {
public static void main(String[] args) {
Path path = Paths.get("output.txt");
List<String> lines = Arrays.asList("Line 1", "Line 2", "Line 3");
try {
Files.write(path, lines);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Notes:
Simple and concise for small files
Overwrites existing content by default
C. Writing Binary Files
import java.io.*;
public class WriteBinaryFile {
public static void main(String[] args) {
byte[] data = {0, 1, 2, 3, 4, 5};
try (FileOutputStream fos = new FileOutputStream("output.bin")) {
fos.write(data);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Notes:
OutputStream writes raw bytes
Useful for images, audio, or other binary formats
4. Best Practices
Use try-with-resources → ensures files are closed automatically
Use BufferedReader/BufferedWriter → better performance for text files
Handle exceptions properly → always catch or throw IOException
Use NIO Files API → cleaner, modern, and supports large files
Avoid hardcoding paths → use Paths.get() for platform independence
Close streams → if not using try-with-resources, always close streams in finally
5. Summary
Reading: BufferedReader, Files.lines, InputStream
Writing: BufferedWriter, Files.write, OutputStream
Text vs Binary: Use character streams for text, byte streams for binary
Modern Java: Prefer java.nio.file.Files and Streams for simplicity and performance
Learn Full Stack JAVA Course in Hyderabad
Read More
Multithreading and Concurrency in Java
Java 8 Features: Lambdas, Streams, and Functional Interfaces
Java Collections Framework: List, Set, Map
Visit Our Quality Thought Institute in Hyderabad
Subscribe by Email
Follow Updates Articles from This Blog via Email
No Comments