【发布时间】:2016-11-28 02:38:37
【问题描述】:
public class Main {
final private static int MAX_RECORD_NUMBER = 20;
final private static int RECORD_LENGTH = 71;
public static void main(String[] args) throws IOException, FileNotFoundException{
Scanner input = new Scanner(System.in);
System.out.println("Please input the file location and name.");
String filepath = input.next();
File file = new File(filepath);
boolean isExisted = file.exists(); // Problem exists here if I delete FileNotFoundException
RandomAccessFile store = new RandomAccessFile(file, "rw");
if (!isExisted) {
String dummy = "Empty record ";
for (int i = 0; i < MAX_RECORD_NUMBER; i++) {
store.writeUTF(dummy);
}
}
我在这里遇到了一个小故障。如果我没有抛出 FileNotFoundException,file.exists() 方法将总是返回 true(即使文件真的不存在)。在这种情况下,如果我不在 main 方法的开头抛出 FileNotFoundException,它就无法将 UTF 写入该文件。这一定是一个愚蠢的问题,但我只想知道这背后的机制是什么。 API 对我也没有帮助。我非常感谢任何可以向我解释的人。
编辑:对不起,我之前不清楚。我真正想问的是,为什么 .exists() 方法总是返回 true 而不是 false 或其他意外错误?
【问题讨论】:
-
你了解检查异常的概念吗?
-
@Dici 是的。所以这都是关于检查异常的吗?我想如果我不抛出检查异常,日食不会让我通过。但是我在编码时没有显示任何错误。
-
您的问题的标题需要改写。请记住,您写的每一个问题都是针对未来的人(以及您)。
-
如果没有
throws子句,您的代码将无法编译,但您的问题似乎告诉我您对这些概念有点不清楚 -
@PhantomPain
FileNotFoundException扩展IOException。
标签: java file-exists