从java中不存在的文本文件读取?
我有一些奇怪的问题,但我希望得到解决 我在java中创建了一个构造函数,当从构造函数类中创建对象时,它从文本文件中读取 如果此文件存在,则即使该文件为空,也会读取其数据 但我希望能找到解决方案来处理(文件不存在)的错误,因为这会使我的程序崩溃 这是我的密码:从java中不存在的文本文件读取?,java,file-io,text-files,Java,File Io,Text Files,我有一些奇怪的问题,但我希望得到解决 我在java中创建了一个构造函数,当从构造函数类中创建对象时,它从文本文件中读取 如果此文件存在,则即使该文件为空,也会读取其数据 但我希望能找到解决方案来处理(文件不存在)的错误,因为这会使我的程序崩溃 这是我的密码: import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.*;
public class Inventory{
public Inventory(){
Scanner x = null;
try{
x = new Scanner(new File("C:\\Users\\فاطمة\\Downloads\\products.txt"));
}
catch(Exception e)
{
System.out.println("No current products.");
}
while(x.hasNext())
{
String a = x.next(); // id
String b = x.next(); // product name
String c = x.next(); // product type
String d = x.next(); // product brand
int e = x.nextInt(); // product quantity
int f = x.nextInt(); // production day
int g = x.nextInt(); // production month
int h = x.nextInt(); // production year
int i = x.nextInt(); // expiry day
int j = x.nextInt(); // expiry month
int k = x.nextInt(); // expiry year
String l = x.next(); // company name
String m = x.next(); // supplier name
String n = x.next(); // supplier address
String p = x.next(); // supplier phone number
}
}
}
查看代码中的逻辑流。即使文件/扫描仪行抛出错误(即,如果未找到该文件),您仍会尝试读取它 您正在寻找的解决方案是
Scanner x = null;
try {
x = new Scanner(new File("C:\\Users\\فاطمة\\Downloads\\products.txt"));
while(x.hasNext()) {
String a = x.next(); // id
String b = x.next(); // product name
String c = x.next(); // product type
String d = x.next(); // product brand
int e = x.nextInt(); // product quantity
int f = x.nextInt(); // production day
int g = x.nextInt(); // production month
int h = x.nextInt(); // production year
int i = x.nextInt(); // expiry day
int j = x.nextInt(); // expiry month
int k = x.nextInt(); // expiry year
String l = x.next(); // company name
String m = x.next(); // supplier name
String n = x.next(); // supplier address
String p = x.next(); // supplier phone number
}
} catch(Exception e) {
System.out.println("No current products.");
}
您应该做的不是捕获异常,而是捕获一个特定的错误,例如,或者,如果您想捕获所有错误,则保持原样,但我建议您检查错误,并使用以下方法向console提供更详细的错误
...
} catch (Exception e) {
if (e instanceof FileNotFoundException) {
System.out.println("could not find the file...");
} else {
System.out.println("something else went wrong");
}
}
请记住,如果while循环在中,请尝试。。。catch
块,读取文件时抛出的错误也将被捕获
捕捉多种类型错误的更明确的方法是
...
} catch (FileNotFoundException e) {
System.out.println("file not found");
} catch (Exception e) {
System.out.println("something else went wrong");
} ...
非常感谢你,兄弟,这真的很有用:)如果它是一个解决方案,请接受这个解决方案作为答案。是的,这肯定是最好的解决方案。接受的解决方案:)为什么要在catch块中使用
instanceof
?声明异常类型有一个原因-.-@Clashsoft如果捕获(异常…
),则捕获扩展异常的任何内容,可以是任何内容。我是说/如果/他想在一个块中显式捕获所有内容(即不try…catch…catch…
),那么就用实例执行它。