2016-03-07 65 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("")) 
       { 

       } 
      } 
     } 

不知道這會幫助,但也許值得一試。