java.util.NoSuchElementException:找不到行 - Scanner / PriintWriter问题

时间:2016-10-07 16:07:21

标签: java

我想使用csv和txt文件批量创建一些批处理脚本,运行时出错。我对代码进行了评论,因此您应该能够从这些说明中确定我的意图。我只是在这里写的更多,因为机器人要求我在发帖之前继续写更多的解释。一旦这个红色文本框消失,我将停止写作,你可以停止阅读。我真的希望你已经停止阅读,因为这会让我感到沮丧,这是肯定的。我开始怀疑是否应该开始一个新的段落。让我们看看是否有帮助。

我感觉可能使用不同的语言会更合适,但我的经验主要限于java,我希望在继续之前用这种语言做得更好。

  

线程“main”中的异常java.util.NoSuchElementException:找不到行       在java.util.Scanner.nextLine(Scanner.java:1540)       at printerscriptcreator.PrinterScriptCreator.main(PrinterScriptCreator.java:29)

public class PrinterScriptCreator {  
    public static void main(String[] args) throws FileNotFoundException {
        File csvFile = new File("printers.csv");
        File txtFile = new File("xeroxTemplate.txt");
        Scanner csvScanner = new Scanner(csvFile);
        csvScanner.useDelimiter(",");
        Scanner txtScanner = new Scanner(txtFile);

        try{
            while(csvScanner.hasNext()){
                //create file with name from first csv cell
                File file = new File(csvScanner.next());
                //create FileWriter to populate the newly created file
                FileWriter fw = new FileWriter(file);
                //create PrintWriter to communicate with FileWriter
                PrintWriter pw = new PrintWriter(fw);
                //copy first 7 lines from xeroxTemplate.txt
                for(int i=0; i<7; i++){
                    pw.println(txtScanner.nextLine());
                }
                //copy the next three cells from CSV into new file
                for(int i=0; i<3; i++){
                    pw.println(csvScanner.next());
                }
                //copy remaining lines from TXT to the new file
                while(txtScanner.hasNextLine()){
                    pw.println(txtScanner.nextLine());
                }
            }  
        } catch (IOException ex) {
            System.out.printf("ERROR: %s\n", ex);
        }    
    }    
}

3 个答案:

答案 0 :(得分:0)

我注意到,您检查hasNext()一次,然后抓取next()三次。您应该在for循环中对hasNext()进行条件限制。

while(csvScanner.hasNext()){

    ...

        //copy the next three cells from CSV into new file
        for(int i=0; i<3; i++){
            pw.println(csvScanner.next());
        }

答案 1 :(得分:0)

Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Scanner.java:1540)
at printerscriptcreator.PrinterScriptCreator.main(PrinterScriptCreator.java:29)

这告诉你发生了什么。你的一个扫描仪试图在没有的时候拉一个nextLine,所以它抛出了这个异常。

它告诉你PrinterScriptCreator.java:29。我没有粘贴的行号,但检查第29行。这是哪一行?我的猜测就是这个:

for(int i=0; i<7; i++){
        pw.println(txtScanner.nextLine());
}

你试图拉7行,但没有7.所以它抛出异常。

你可以尝试做类似

的事情
for(int i=0; i<7; i++){
    if(txtScanner.hasNextLine()){
            pw.println(txtScanner.nextLine());
    }
}

或者您可以尝试使用try-catch块来处理它。无论哪种方式,检查您的文件,并确保他们有正确的数据。

答案 2 :(得分:-1)

需要在while循环中创建txtScanner,以便在每次创建文件后重新创建它。否则它会用完线。