Reading and Writing Files in Java
Includes detailed example code for
FileInputStream and
FileOutputStream
Overview
• Byte streams (FileInputStream, FileOutputStream) — basic file I/O
• Exceptions: FileNotFoundException, IOException, SecurityException
• Closing files: close(), finally block, try-with-resources (JDK 7+)
• Examples: reading, writing, copying files, and best practices
Reading a File (traditional, finally)
import java.io.*;
public class ShowFile {
public static void main(String[] args) {
FileInputStream fin = null;
if (args.length != 1) {
System.out.println("Usage: java ShowFile filename");
return;
}
try {
fin = new FileInputStream(args[0]);
int i;
while ((i = fin.read()) != -1) {
System.out.print((char) i);
}
} catch (FileNotFoundException e) {
System.out.println("File not found: " + e);
} catch (IOException e) {
System.out.println("I/O Error: " + e);
} finally {
try {
if (fin != null) fin.close();
} catch (IOException e) {
System.out.println("Error closing file: " + e);
} Reads one byte at a time using read(); uses finally to ensure close().
}
}
}
Reading a File (try-with-resources)
import java.io.*;
public class ShowFileTryWithResources {
public static void main(String[] args) {
if (args.length != 1) {
System.out.println("Usage: java ShowFileTryWithResources filename");
return;
}
try (FileInputStream fin = new FileInputStream(args[0])) {
int i;
while ((i = fin.read()) != -1) {
System.out.print((char) i);
}
} catch (IOException e) {
System.out.println("I/O Error: " + e);
}
}
}
Automatic resource management — fin is closed automatically.
Copying a File (buffered)
import java.io.*;
public class CopyFile {
public static void main(String[] args) {
if (args.length != 2) {
System.out.println("Usage: java CopyFile srcFile destFile");
return;
}
try (FileInputStream in = new FileInputStream(args[0]);
FileOutputStream out = new FileOutputStream(args[1])) {
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = in.read(buffer)) != -1) {
out.write(buffer, 0, bytesRead);
}
} catch (IOException e) {
System.out.println("I/O Error: " + e);
}
}
}
Use a byte[] buffer for efficiency instead of reading one byte at a time.
Writing to a File
import java.io.*;
public class WriteText {
public static void main(String[] args) {
String data = "Hello, File I/O!\n";
try (FileOutputStream out = new FileOutputStream("output.txt")) {
out.write(data.getBytes()); // writes bytes of the string
} catch (IOException e) {
System.out.println("I/O Error: " + e);
}
}
}
Converts String to bytes using getBytes(); FileOutputStream overwrites existing file.
Exception Handling & Best
Practices
• Catch IOException to handle FileNotFoundException and other I/O errors together.
• Prefer try-with-resources for simpler, safer code (auto-close).
• Use buffered reads/writes (byte[] buffer) for efficiency.
• Always validate input (check args, file permissions) and report useful messages.