如果文件不存在,处理创建文件的首选方法
Preferred way to handle creating a file if it doesn't exist
我正在编写一个程序来检查文件是否存在。如果它不存在,它会创建它。在此之后,它读取文件。但是,当我尝试为其创建扫描仪时,我在 Eclipse 中得到了 "unhandled FileNotFoundException error"。这是代码片段:
if(!NETWORK_FILE.exists()){
try {
NETWORK_FILE.createNewFile();
}catch(IOException e) {
e.printStackTrace();
}
}else{
//"ERROR" IS ON THE LINE BELOW
Scanner read = new Scanner(NETWORK_FILE);
while(read.hasNextLine()) {
String fileSerial = read.nextLine();
if(fileSerial.equals(serial)) {
System.out.println("serial already exists");
return;
}
}
read.close();
}
我认为捕获 FileNotFoundException 毫无意义,因为我在此之前专门检查并创建了文件。有"preferred way"这样做吗?
你的问题很有道理。
但是已检查的异常以这种方式工作。
编译器不会在不同的逻辑处理之间建立任何关联。
另请注意,应用程序可以是多线程的,文件系统可以由多个进程共享。
一次存在的文件可能在1秒后不再存在。
在这种特定情况下,我认为我会提取特定方法中的异常处理,例如 createScannerWithExistingFile()
会抛出 RuntimeException
。这将使整体代码逻辑
通过隔离此 catch
语句更清晰:
if (!NETWORK_FILE.exists()) {
...
}
else {
Scanner read = createScannerWithExistingFile(NETWORK_FILE);
while (read.hasNextLine()) {
String fileSerial = read.nextLine();
if (fileSerial.equals(serial)) {
System.out.println("serial already exists");
return;
}
}
read.close();
}
private Scanner createScannerWithExistingFile(File file) {
try {
return new Scanner(file);
} catch (FileNotFoundException e) {
throw new RuntimeException("file " + f + " should exist", e);
}
}
我正在编写一个程序来检查文件是否存在。如果它不存在,它会创建它。在此之后,它读取文件。但是,当我尝试为其创建扫描仪时,我在 Eclipse 中得到了 "unhandled FileNotFoundException error"。这是代码片段:
if(!NETWORK_FILE.exists()){
try {
NETWORK_FILE.createNewFile();
}catch(IOException e) {
e.printStackTrace();
}
}else{
//"ERROR" IS ON THE LINE BELOW
Scanner read = new Scanner(NETWORK_FILE);
while(read.hasNextLine()) {
String fileSerial = read.nextLine();
if(fileSerial.equals(serial)) {
System.out.println("serial already exists");
return;
}
}
read.close();
}
我认为捕获 FileNotFoundException 毫无意义,因为我在此之前专门检查并创建了文件。有"preferred way"这样做吗?
你的问题很有道理。
但是已检查的异常以这种方式工作。
编译器不会在不同的逻辑处理之间建立任何关联。
另请注意,应用程序可以是多线程的,文件系统可以由多个进程共享。
一次存在的文件可能在1秒后不再存在。
在这种特定情况下,我认为我会提取特定方法中的异常处理,例如 createScannerWithExistingFile()
会抛出 RuntimeException
。这将使整体代码逻辑
通过隔离此 catch
语句更清晰:
if (!NETWORK_FILE.exists()) {
...
}
else {
Scanner read = createScannerWithExistingFile(NETWORK_FILE);
while (read.hasNextLine()) {
String fileSerial = read.nextLine();
if (fileSerial.equals(serial)) {
System.out.println("serial already exists");
return;
}
}
read.close();
}
private Scanner createScannerWithExistingFile(File file) {
try {
return new Scanner(file);
} catch (FileNotFoundException e) {
throw new RuntimeException("file " + f + " should exist", e);
}
}