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 [Link].*;
public class ShowFile {
public static void main(String[] args) {
FileInputStream fin = null;
if ([Link] != 1) {
[Link]("Usage: java ShowFile filename");
return;
}
try {
fin = new FileInputStream(args[0]);
int i;
while ((i = [Link]()) != -1) {
[Link]((char) i);
}
} catch (FileNotFoundException e) {
[Link]("File not found: " + e);
} catch (IOException e) {
[Link]("I/O Error: " + e);
} finally {
try {
if (fin != null) [Link]();
} catch (IOException e) {
[Link]("Error closing file: " + e);
} Reads one byte at a time using read(); uses finally to ensure close().
}
}
}
Reading a File (try-with-resources)
import [Link].*;
public class ShowFileTryWithResources {
public static void main(String[] args) {
if ([Link] != 1) {
[Link]("Usage: java ShowFileTryWithResources filename");
return;
}
try (FileInputStream fin = new FileInputStream(args[0])) {
int i;
while ((i = [Link]()) != -1) {
[Link]((char) i);
}
} catch (IOException e) {
[Link]("I/O Error: " + e);
}
}
}
Automatic resource management — fin is closed automatically.
Copying a File (buffered)
import [Link].*;
public class CopyFile {
public static void main(String[] args) {
if ([Link] != 2) {
[Link]("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 = [Link](buffer)) != -1) {
[Link](buffer, 0, bytesRead);
}
} catch (IOException e) {
[Link]("I/O Error: " + e);
}
}
}
Use a byte[] buffer for efficiency instead of reading one byte at a time.
Writing to a File
import [Link].*;
public class WriteText {
public static void main(String[] args) {
String data = "Hello, File I/O!\n";
try (FileOutputStream out = new FileOutputStream("[Link]")) {
[Link]([Link]()); // writes bytes of the string
} catch (IOException e) {
[Link]("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.