Java FileNotFoundException
Opening a missing file with FileInputStream raises FileNotFoundException. Older stream APIs also use this exception when an existing file cannot be opened.
A simple example
FileNotFoundException
- Start with No file named a.txt
- Do this Open a.txt for reading
- Result File missing
Syntax
new FileInputStream(file)
Run these examples in Java
Save one example at a time as Main.java. Use JDK 21.
java Main.javaOpen the first receipt of the day
A new checkout starts with an empty receipt folder. When the cashier asks to reprint today's first receipt, the app should explain that a receipt has yet to be saved.
import java.nio.file.Files;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
class Main {
public static void main(String[] args) throws Exception {
var folder = Files.createTempDirectory("checkout-");
try (var receipt = new FileInputStream(folder.resolve("today.txt").toFile())) {
System.out.println(receipt.read());
} catch (FileNotFoundException absent) {
System.out.println("No receipt yet");
} finally {
Files.delete(folder);
}
}
}
No receipt yet
The example creates an empty directory, so it knows this particular open failed because the receipt is absent.
Reprint a receipt after the sale
A cashier completes the first sale and saves its receipt. The reprint button should now open the saved record and show its first line to the customer.
import java.nio.file.Files;
import java.io.FileInputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
class Main {
public static void main(String[] args) throws Exception {
var receipt = Files.createTempFile("paid-", ".txt");
try {
Files.writeString(receipt, "Paid 12");
try (var reader = new BufferedReader(new InputStreamReader(
new FileInputStream(receipt.toFile()), StandardCharsets.UTF_8))) {
System.out.println(reader.readLine());
}
} finally {
Files.deleteIfExists(receipt);
}
}
}
Paid 12
The reader is closed before the example removes its own temporary receipt.
Read a saved shift record
The closing clerk saved the file before leaving. Open the expected file and show the desk whether it is available.
Code and output in Java
import java.util.*;
import java.io.*;
import java.nio.file.*;
import java.util.concurrent.*;
class Main {
public static void main(String[] args) throws Exception {
Path dir=Files.createTempDirectory("lesson-");
Path file=dir.resolve("record.txt");
try {
Files.writeString(file,"Ready");
Files.readString(file);
System.out.println("File available");
} catch (NoSuchFileException e) {
System.out.println("Ask for the file");
} finally {
Files.deleteIfExists(file);
Files.deleteIfExists(dir);
}
}
}
File available
What to watch for
A missing name is only one possible cause. The NIO APIs can report more specific failures, such as NoSuchFileException.