Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/368.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 验证文件时是否应使用异常来产生自定义错误?_Java - Fatal编程技术网

Java 验证文件时是否应使用异常来产生自定义错误?

Java 验证文件时是否应使用异常来产生自定义错误?,java,Java,我正在读取一个文本文件,当文件中的信息不正确时,我希望生成自定义错误 当前,扫描文件并在控制台中显示其内容的代码如下: String importFile = ""; //I use multiple System.out.prints, just because it's less cluttered for me. System.out.println("Please specify the directory of the file you would like to import");

我正在读取一个文本文件,当文件中的信息不正确时,我希望生成自定义错误

当前,扫描文件并在控制台中显示其内容的代码如下:

String importFile = "";

//I use multiple System.out.prints, just because it's less cluttered for me.
System.out.println("Please specify the directory of the file you would like to import");
System.out.println("Format should be as follows 'C:\\Users\\Example\\Example.txt'");
System.out.print("Please enter the directory: ");
importFile = keyboard.nextLine();
System.out.println("-------------------------------");
System.out.println("\tThe summary of the books in the imported catalogue is as follows");
System.out.print("===============================================================================");
System.out.format("\n|%1$-18s|%2$-25s|%3$-6s|%4$-14s|%5$-10s|","Title", "Author", "Price", "Publisher", "ISBN");
System.out.print("\n===============================================================================");

File Fileobject = new File(importFile);

try {
    Scanner fileReader = new Scanner(Fileobject);
    while(fileReader.hasNext()) {
        String line = fileReader.nextLine();
        String[] splitText = line.split("\\s-\\s");
        System.out.format("\n|%1$-18s|%2$-25s|%3$-6s|%4$-14s|%5$-10s|", splitText[0], splitText[1], splitText[2], splitText[3], splitText[4]);
    }
    fileReader.close();
} catch (FileNotFoundException e) { 
    System.out.println("File does not exist"); 
}
String - String - Double - String - String
如图所示,标题、作者、价格、出版商和ISBN存储在splitText的不同位置,并以整洁的表格打印到控制台

目前,文件中的格式如下:

String importFile = "";

//I use multiple System.out.prints, just because it's less cluttered for me.
System.out.println("Please specify the directory of the file you would like to import");
System.out.println("Format should be as follows 'C:\\Users\\Example\\Example.txt'");
System.out.print("Please enter the directory: ");
importFile = keyboard.nextLine();
System.out.println("-------------------------------");
System.out.println("\tThe summary of the books in the imported catalogue is as follows");
System.out.print("===============================================================================");
System.out.format("\n|%1$-18s|%2$-25s|%3$-6s|%4$-14s|%5$-10s|","Title", "Author", "Price", "Publisher", "ISBN");
System.out.print("\n===============================================================================");

File Fileobject = new File(importFile);

try {
    Scanner fileReader = new Scanner(Fileobject);
    while(fileReader.hasNext()) {
        String line = fileReader.nextLine();
        String[] splitText = line.split("\\s-\\s");
        System.out.format("\n|%1$-18s|%2$-25s|%3$-6s|%4$-14s|%5$-10s|", splitText[0], splitText[1], splitText[2], splitText[3], splitText[4]);
    }
    fileReader.close();
} catch (FileNotFoundException e) { 
    System.out.println("File does not exist"); 
}
String - String - Double - String - String
文件中的一些错误可能包括:

  • 使用了错误的分隔符(当前信息在每个连字符处拆分(前面是空格,后面是空格))

  • 信息不正确(如信息缺失)

我希望不仅能够跟踪错误信息所在的位置,而且能够在最后打印出文件中有多少错误(如果可能的话,只加上没有任何错误的有效条目。如图所示,当文件无效/输入的路径在其中无效时,我有一个错误-所以这就包括在内了


任何帮助都将不胜感激。

编写两个方法,例如
logSuccess
logError
。在这两个方法中增加计数器。将计数器作为实例变量放入类中。将
println
行也放入这些方法中

最后,您可以根据需要打印摘要


如果您自己的业务逻辑将定义文件中的条目是否良好,则编写一个
validate
方法,该方法将定义关于条目有效性的所有条件,如果所有条件都已通过,则调用
logSuccess
,否则从va调用
logError
方法lidate方法。在现有代码中从此循环中调用validate方法。

编写两个方法,例如
logSuccess
logError
。在这两个方法中,递增计数器。将计数器作为实例变量放入类中。将
println
行也放入这些方法中

最后,您可以根据需要打印摘要


如果您自己的业务逻辑将定义文件中的条目是否良好,则编写一个
validate
方法,该方法将定义关于条目有效性的所有条件,如果所有条件都已通过,则调用
logSuccess
,否则从va调用
logError
方法lidate方法。在现有代码中从此循环中调用validate方法。

由于程序的目的是优雅地处理错误,因此接收无效输入可能被视为程序正常流程的一部分。另一方面,您也可以认为无效输入是一个例外,您的程序知道如何处理它因此,有两种同样好的方法是可能的

我更喜欢使用异常的第二种方法。它如下所示:您定义一个
Book
对象,该对象具有一个静态工厂方法,用于从
String
创建
Book
。您还定义一个自定义异常,并将其声明为工厂方法签名的一部分:

class Book {
    private Book(String title, String author, String publisher, double price, String isbn) {
        ...
    }
    public Book parse(String bookDef) throws InvalidBookException {
        ...
    }
}
现在,您的
main
方法可以循环遍历文件中的字符串,解析书籍,并在遍历文件时捕获
invalidbookeexception
异常。异常可以提供有关输入错误的信息;
main
应该保留行号,以便在末尾提供详细输出:

int lineNumber = 0;
List<String> warnings = new ArrayList<>();
while(fileReader.hasNext()) {
    lineNumber++;
    try {
        Book b = Book.parse(fileReader.nextLine());
        ... // Print the content of b
    } catch (InvalidBookException ibe) {
        String message = "Line "+lineNumber+": "+ibe.getMessage();
        warnings.add(message);
    }
}
if (!warnings.isEmpty()) {
    ... // Display warnings
}
int lineNumber=0;
列表警告=新建ArrayList();
while(fileReader.hasNext()){
lineNumber++;
试一试{
Book b=Book.parse(fileReader.nextLine());
…//打印b的内容
}捕获(InvalidBookException ibe){
String message=“Line”+lineNumber+:“+ibe.getMessage();
警告。添加(消息);
}
}
如果(!warnings.isEmpty()){
…//显示警告
}

由于您的程序旨在优雅地处理错误,因此接收无效输入可能被视为程序正常流程的一部分。另一方面,您也可以认为无效输入是一种例外,您的程序知道如何从中恢复。因此,有两种同样好的方法是可能的

我更喜欢使用异常的第二种方法。它如下所示:您定义一个
Book
对象,该对象具有一个静态工厂方法,用于从
String
创建
Book
。您还定义一个自定义异常,并将其声明为工厂方法签名的一部分:

class Book {
    private Book(String title, String author, String publisher, double price, String isbn) {
        ...
    }
    public Book parse(String bookDef) throws InvalidBookException {
        ...
    }
}
现在,您的
main
方法可以循环遍历文件中的字符串,解析书籍,并在遍历文件时捕获
invalidbookeexception
异常。异常可以提供有关输入错误的信息;
main
应该保留行号,以便在末尾提供详细输出:

int lineNumber = 0;
List<String> warnings = new ArrayList<>();
while(fileReader.hasNext()) {
    lineNumber++;
    try {
        Book b = Book.parse(fileReader.nextLine());
        ... // Print the content of b
    } catch (InvalidBookException ibe) {
        String message = "Line "+lineNumber+": "+ibe.getMessage();
        warnings.add(message);
    }
}
if (!warnings.isEmpty()) {
    ... // Display warnings
}
int lineNumber=0;
列表警告=新建ArrayList();
while(fileReader.hasNext()){
lineNumber++;
试一试{
Book b=Book.parse(fileReader.nextLine());
…//打印b的内容
}捕获(InvalidBookException ibe){
String message=“Line”+lineNumber+:“+ibe.getMessage();
警告。添加(消息);
}
}
如果(!warnings.isEmpty()){
…//显示警告
}

我不清楚你到底在问什么。如果你有特定的逻辑来定义数据应该是什么,你能不能写一些
If
语句来表达该逻辑并检查数据?例如,如果使用了错误的分隔符或出现了错误的字段数,那么
splitText
将有错误的n元素数。你可以编写一个
if
来检查
拆分文本的长度,并做出相应的响应。@David-基本上我想