Прежде всего вы можете захотеть избегать использования тех же имен классов, что и существующие классы Java, чтобы избежать путаницы.
В вашем методе main
вы захотите проверить, существует ли файл перед вамииспользуйте создать объект Scanner
.
Кроме того, нет необходимости во всех exists = false
, где вы будете выдавать исключение, поскольку код останавливается там.
Возможное решение будетследующим образом:
public static boolean fileExists(File file) throws FileNotFoundException {
String fileName = file.getName(); // for displaying file name as a String
if (!(file.exists())) {
throw new FileNotFoundException("The file " + fileName + " does not exist.");
}
if (!(file.isFile())) {
throw new FileNotFoundException("The file " + fileName + " is not a normal file.");
}
if (!(file.canRead())) {
throw new FileNotFoundException("The file " + fileName + " is not readable.");
}
return true;
}
public static void main(String[] args) throws Exception {
String INPUT_FILE = "file.txt";
try {
File inputFile = new File(INPUT_FILE);
if (fileExists(inputFile)) {
Scanner input = new Scanner(inputFile);
System.out.println("The file " + INPUT_FILE + " exists. Testing continues below.");
}
} catch (FileNotFoundException ex) {
System.err.println(ex.getMessage());
}
}