The java.io package provides system input and output through data streams, serialization, and the file system. It contains classes for reading and writing data to files, network connections, and other I/O sources.
// Reading a filetry (FileInputStream fis = new FileInputStream("input.bin")) { int data; while ((data = fis.read()) != -1) { // Process byte }} catch (IOException e) { e.printStackTrace();}// Reading into buffertry (FileInputStream fis = new FileInputStream("input.bin")) { byte[] buffer = new byte[1024]; int bytesRead; while ((bytesRead = fis.read(buffer)) != -1) { // Process buffer[0..bytesRead-1] }}
Writes bytes to a file in the file system.
// Writing to a file (overwrites existing)try (FileOutputStream fos = new FileOutputStream("output.bin")) { fos.write("Hello".getBytes());} catch (IOException e) { e.printStackTrace();}// Appending to a filetry (FileOutputStream fos = new FileOutputStream("output.bin", true)) { fos.write("More data".getBytes());}// Writing byte arraybyte[] data = {1, 2, 3, 4, 5};try (FileOutputStream fos = new FileOutputStream("data.bin")) { fos.write(data);}
Convenience class for reading character files using default character encoding.
// Reading a text filetry (FileReader reader = new FileReader("input.txt")) { int ch; while ((ch = reader.read()) != -1) { System.out.print((char) ch); }}// With specific encoding (Java 11+)try (FileReader reader = new FileReader("input.txt", StandardCharsets.UTF_8)) { // Read file}
Convenience class for writing character files.
// Writing to a text filetry (FileWriter writer = new FileWriter("output.txt")) { writer.write("Hello, World!\n"); writer.write("Second line\n");}// Appendingtry (FileWriter writer = new FileWriter("output.txt", true)) { writer.write("Appended text\n");}
// Buffered binary readingtry (BufferedInputStream bis = new BufferedInputStream( new FileInputStream("large-file.bin"))) { byte[] buffer = new byte[8192]; int bytesRead; while ((bytesRead = bis.read(buffer)) != -1) { // Process buffer }}// Buffered binary writingtry (BufferedOutputStream bos = new BufferedOutputStream( new FileOutputStream("output.bin"))) { bos.write(data); // No need to manually flush, try-with-resources handles it}
BufferedReader reads text from a character-input stream, buffering characters for efficient reading.
// Reading lines from a filetry (BufferedReader reader = new BufferedReader( new FileReader("input.txt"))) { String line; while ((line = reader.readLine()) != null) { System.out.println(line); }}// Using streams (Java 8+)try (BufferedReader reader = new BufferedReader( new FileReader("input.txt"))) { reader.lines() .filter(line -> line.contains("important")) .forEach(System.out::println);}// Reading from standard inputBufferedReader stdin = new BufferedReader( new InputStreamReader(System.in));System.out.print("Enter name: ");String name = stdin.readLine();
BufferedWriter
BufferedWriter writes text to a character-output stream, buffering characters for efficient writing.
// Writing lines to a filetry (BufferedWriter writer = new BufferedWriter( new FileWriter("output.txt"))) { writer.write("First line"); writer.newLine(); writer.write("Second line"); writer.newLine();}// Writing multiple linesList<String> lines = Arrays.asList("Line 1", "Line 2", "Line 3");try (BufferedWriter writer = new BufferedWriter( new FileWriter("output.txt"))) { for (String line : lines) { writer.write(line); writer.newLine(); }}
Provides random access to file contents (both reading and writing).
try (RandomAccessFile raf = new RandomAccessFile("data.bin", "rw")) { // Write at current position raf.writeInt(42); raf.writeDouble(3.14159); // Get current position long position = raf.getFilePointer(); // Seek to specific position raf.seek(0); // Go to beginning // Read from current position int value = raf.readInt(); double pi = raf.readDouble(); // Get file length long length = raf.length(); // Set file length (truncate or extend) raf.setLength(1024);}
import java.io.*;import java.util.*;public class FileIOExample { // Copy a file using byte streams public static void copyFile(String source, String dest) throws IOException { try (InputStream in = new BufferedInputStream( new FileInputStream(source)); OutputStream out = new BufferedOutputStream( new FileOutputStream(dest))) { byte[] buffer = new byte[8192]; int bytesRead; while ((bytesRead = in.read(buffer)) != -1) { out.write(buffer, 0, bytesRead); } } } // Read all lines from a text file public static List<String> readAllLines(String filename) throws IOException { List<String> lines = new ArrayList<>(); try (BufferedReader reader = new BufferedReader( new FileReader(filename))) { String line; while ((line = reader.readLine()) != null) { lines.add(line); } } return lines; } // Write lines to a text file public static void writeLines(String filename, List<String> lines) throws IOException { try (PrintWriter writer = new PrintWriter( new BufferedWriter(new FileWriter(filename)))) { for (String line : lines) { writer.println(line); } } } // Process large file line by line public static void processLargeFile(String filename) throws IOException { try (BufferedReader reader = new BufferedReader( new FileReader(filename))) { reader.lines() .filter(line -> !line.isEmpty()) .map(String::toUpperCase) .forEach(System.out::println); } }}
Always use try-with-resources when working with I/O streams to ensure proper resource cleanup, even if exceptions occur.
For modern file operations, consider using the java.nio.file package (Files, Paths) which provides a more powerful and easier-to-use API.