这意味着当您调用 时new PrintWriter(file)
,当您要写入的文件不存在时,它可能会引发异常。因此,您要么需要处理该异常,要么让您的代码重新抛出它以供调用者处理。
import java.io.*;
public class Testing {
/**
* This writes a string to a file.
* If an exception occurs, we don't care if nothing gets written.
*/
public void writeToFileWithoutThrowingExceptions(File file, String text) {
// Yes, we could use try-with-resources here,
// but that would muddy the example.
PrintWriter printWriter;
try {
printwriter = new PrintWriter(file);
printWriter.println(text);
} catch (FileNotFoundException fnfe) {
// Do something with that exception to handle it.
// Since we said we don't care if our text does not get written,
// we just print the exception and move on.
// Printing the exception like this is usually a bad idea, since
// now no-one knows about it. Logging is better, but even better
// is figuring out what we need to do when that exception occurs.
System.out.println(fnfe);
} finally {
// Whether an exception was thrown or not,
// we do need to close the printwriter.
printWriter.close();
}
}
/**
* This writes a string to a file.
* If an exception occurs, we re-throw it and let the caller handle it.
*/
public void writeToFileThrowingExceptions(File file, String text) throws FileNotFoundException {
// We use try-with-resources here. This takes care of closing
// the PrintWriter, even if an exception occurs.
try (PrintWriter printWriter = new PrintWriter(file)) {
printWriter.println(text);
}
}
public static void main(String[] args) {
File file = new File("file.txt");
file.getParentFile().mkdirs();
// We call the method that doesn't throw an exception
writeToFileWithoutThrowingExceptions(file, "Hello");
// Then we call the method that _can_ throw an exception
try {
writeToFileThrowingExceptions(file, "World");
} catch (FileNotFoundException fnfe) {
// Since this method can throw an exception, we need to handle it.
// Note that now we have different options for handling it, since
// we are now letting the caller handle it.
// The caller could decide to try and create another file, send
// an e-mail, or just log it and move on.
// Again, as an example, we just print the exception, but as we
// discussed, that is not the best way of handling one.
System.out.println(fnfe);
}
}
}