2016-03-07 63 views
0

我已经从一个文本文件扫描了各行,现在需要将行分隔为四个不同的字符串,然后将它们添加到数组中。任何帮助我在这里做错了吗?试图扫描已经扫描的文件中的一行字符串

public void method()throws FileNotFoundException{ 

    FileDialog fileBox = new FileDialog(mainWindow,"Open", FileDialog.LOAD); 
    fileBox.setVisible(true); 
    fileBox.setDirectory("."); 
    String dataFile = fileBox.getFile(); 
    Scanner scanner = new Scanner(new File(dataFile)); 
    while(scanner.hasNext()) 
    { 
     String lineOfInput = scanner.nextLine(); 
     if (lineOfInput.startsWith("/") || lineOfInput.startsWith("[") && lineOfInput !=null) 
     scanner.nextLine(); 
     else 
     { 
      String newLineOfInput = lineOfInput.trim(); 
      System.out.println(newLineOfInput); 
      Scanner newScanner = new Scanner(newLineOfInput); 
      while(newScanner.hasNext()) 
      { 
       String group = scanner.next(); 
       String vehID = scanner.next(); 
       String regNo = scanner.next(); 
       String make = scanner.next(); 
       storeVehicle(new Vehicle(group, vehID, regNo,make)); 
       newScanner.close(); 
      } 
     } 
     scanner.close(); 

    }   
+0

您应该指定正在发生的事情。 –

回答

0

通过问题只是掠过......在下面的代码似乎像scanner应该是newScanner代替。

String group = scanner.next(); 
String vehID = scanner.next(); 
String regNo = scanner.next(); 
String make = scanner.next(); 

因为您想使用存储在变量newLineOfInput下的行;我假设?

更好的选择是使用String#split函数。您不会创建一个全新的对象。它会去是这样的:

String[] lines = newLineOfInput.split(" "); // Splits the string into a string array separated at every 'Space' character. 
String group = lines[0]; 
String vehID = lines[1]; 
... 
+0

不是问题,但谢谢! –

+0

不幸的是我需要使用第二扫描仪, –

+0

控制台显示这条消息在运行时 - 异常线程“main” java.lang.IllegalStateException:扫描仪关闭 \t在java.util.Scanner.ensureOpen(来源不明) \t在Test.main(Test.java:16) –

0

试试这个

  File file = new File(".txt"); 
     Scanner in = null; 
     try 
     { 
      in = new Scanner(file); 
      while(in.hasNext()) 
      { 
       String line = in.nextLine(); 
       if(line.contains("")) 
       { 

       } 
      } 
     } 

不知道这会帮助,但也许值得一试。