如何通过读取 java 中的文件来处理空字符串

how to handle in empty string from reading a file in java

该项目是从文件 ex2 中读取的。 我使用定界符分隔两个字符串。 但是当我到达第 4 行(complex#)时,我得到了一个 NoSuchElementException()。 我想从文件中读取该行,但是要创建我自己的异常。 而不是 NoSuchElementException()。 我该怎么做?

     public static void main(String[] args) throws FileNotFoundException {
    
            List<Polynom<Double>> listDouble;
            List<Polynom<Complex>> listComplex;
            SortedSet<Polynom<Double>> setDouble;
            SortedSet<Polynom<Complex>> setComplex;
    
            int countLines =1;
            Scanner lineScan = null;
            String line = null;
            Scanner sc = new Scanner(new File("ex2.txt"));
            while (sc.hasNextLine()){
                try{
                    line = sc.nextLine();
                    lineScan = new Scanner (line);
                    lineScan.useDelimiter("#");
                    String type = lineScan.next();
                    String value = lineScan.next();
    
    } catch (Exception e) {
                    e.printStackTrace();
                }
'''
this is the file ex2:
complex#[7,(1+5i)]
double#[0,1.0][3,-2]
aaa#[0,1.0][3,-2]
complex#
double#[0,1.0][3,-2]#[-2,1.0]
double#[-2,1.0]
complex#[7,-(1+5i)]
complex#7,(1+5i)
'''

当您从文件中读取一行后,您可以使用 String.split(“定界符”)-> Returns 一个数组。

无需扫描内存中已有的行。

int countLines = 1;
Scanner lineScan = null;
String line = null;
Scanner sc = new Scanner(new File("ex2.txt"));
while (sc.hasNextLine()) {
    try {
        line = sc.nextLine();              
        String[] array = line.split("#");
                
        if(array.length == 1){
            System.out.println("Line (1 element): " + array[0]);
        } else if(array.length == 2){
            System.out.println("Line (2 elements): " + array[0] + " / " + array[1]);
        } else if(array.length == 3){
            System.out.println("Line (3 elements): " + array[0] + " / " + array[1] + " / " + array[2]);
        }
    } catch (Exception e) {
         e.printStackTrace();
    }
}

你可以这样做:

    int countLines =1;
    Scanner lineScan = null;
    String line = null;
    Scanner sc = new Scanner(new File("ex2.txt"));
    while (sc.hasNextLine()){
        try{
            line = sc.nextLine();
            String[] arr = line.split("#");
            if(arr.length < 2) {
                throw MyCustomException;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

这将检查您从 line.split("#") 获得的数组是否少于 2 个值,如果少于 2 个则抛出您自己的异常。