2016-10-07 138 views
0

我想使用csv和txt文件批量创建一些批处理脚本,并且运行时出现错误。我评论了代码,所以你应该能够从这些笔记中确定我的意图。我只在这里写更多的东西,因为机器人要求我在写文章之前不断写更多的解释。一旦这个红色的文本框消失,我会停止写作,你可以停止阅读。我真的希望你已经停止阅读,因为这会让我感到沮丧,这是肯定的。我开始想知道我是否应该开始一个新的段落。让我们看看是否有帮助。java.util.NoSuchElementException:No line found - Scanner/PriintWriter问题

我觉得可能使用不同的语言对此更合适,但是我的经验大多局限于java,我希望在继续之前使用这种语言来获得更好的效果。

在线程 “主” java.util.NoSuchElementException例外:无线发现 在java.util.Scanner.nextLine(Scanner.java:1540) 在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); 
     }  
    }  
} 
+1

Java对此非常好,不需要使用其他语言。 – SpacePrez

回答

-1

需要在while循环中创建txtScanner,以便在创建每个文件后重新创建txtScanner。否则,它会耗尽线条。

+0

这听起来不像是正确的解决方案。你不应该这样做。重新创建它一遍又一遍地读取相同的行,对吧? 你的输入数据是什么样的? – SpacePrez

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()); 
     } 
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) 

这告诉你发生了什么。其中一个扫描仪在没有一个扫描仪时试图拉下一个下一个线,所以它会抛出这个异常。

它告诉你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块来处理它。无论哪种方式,检查您的文件,并确保他们有正确的数据。

+0

需要在while循环中创建txtScanner,以便在创建每个文件后重新创建它。否则,它会耗尽线条。 – Dumpfood

+0

这听起来不对。 – SpacePrez

相关问题