In the following SSCCE, I do not get a FileNotFoundException even if I delete this file from the given location/path i.e. "D:\\Eclipse Workspaces\\SAMPLES AND OTHER SNIPPETS\\SoapCallResults.txt"
Rather the PrintWriter seems to create the file if it is not found.
If the Printwriter creates the file if it is not found, why do we try to handle the FileNotFoundException (compiler complains if we don't surround it with try/catch or add a throws clause) when it is never going to be thrown?
package com.general_tests;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
public class PrintWriterFileNotFoundExceptionTest {
public static void main(String[] args) {
String myName = "What ever my name is!";
PrintWriter printWriter = null;
try {
printWriter = new PrintWriter("D:\\Eclipse Workspaces\\SAMPLES AND OTHER SNIPPETS\\SoapCallResults.txt");
printWriter.println(myName);
} catch (FileNotFoundException e) {
System.out.println("FILE NOT FOUND EXCEPTION!");
e.printStackTrace();
} finally {
if (printWriter != null) { printWriter.close(); }
}
}
}
Replace
Eclipse Workspacesin your path withfooand see if you get the exception. The file itself may be created, but not the whole path above it.You can also leave the path exactly as it is, but set read-only, hidden, and system attributes on the file. The OS will not be able to either write or create it.
Another variation: modify the file's ACL so your user doesn't have the write permission.
There are many more.