2013-05-31 62 views
0

我的代碼不是從文件讀取行。但我不知道爲什麼。初級Java,任何輸入都很有幫助。java故障從文件讀取行

謝謝。

public class ReverseWords { 

public static void main(String [] args){ 
    Scanner in = new Scanner(System.in); 
    System.out.print("Enter File Name: "); 
    String fileName = in.nextLine(); 
    File f = new File(fileName); 
    try { 
     Scanner input = new Scanner(f); 
        int n = input.nextInt(); 
     String line = input.nextLine(); 
      System.out.println(line); 
      String [] words = line.split(" "); 

      for(int i=0; i<words.length; i++){ 
       System.out.println(words[i]); 

      } 


      } catch (FileNotFoundException e) { 
     e.printStackTrace(); 
    } 

}  
+2

請問你的文件的內容樣子?我懷疑問題是nextInt()不是直到最後一行讀取行(它留下新的行標記),所以第一個'nextLine()'返回空字符串(因爲它是Scanner在新行之前唯一可以找到的東西標記),第二個nextLine()將讀取正確的數據。 – Pshemo

+1

我認爲問題在於閱讀int。嘗試刪除行'int in = input.nextInt();' – 2013-05-31 17:19:55

+1

您能顯示文件的內容嗎? –

回答

1

沒有文件內容我只能猜測。

nextInt()不會更改Scanner中的行計數器,因此nextLine()調用將返回當前行的其餘行。 這可能不是你想要的,這是爲什麼沒有行被讀取的原因。

爲了避免這種情況,你可以明確後做一個額外的nextLine()呼叫改變行計數器您nextInt()

int n = input.nextInt(); 
input.nextLine(); 
String line = input.nextLine(); 

Scanner.nextLine API文檔:

此方法返回當前行的其餘部分,最後不包括任何行 分隔符。

0

我假設你有filenotfound異常。

你必須指定絕對路徑作爲輸入。

drive:/sample/input.txt 

首先嚐試從直接

Scanner sc = new Scanner(new File("drive:/dir/file")); 

讀取源文件,也可以地方你的項目中存在的文件。 [該文件夾被命名爲項目名稱] 在這種情況下,您可以只需指定「file.extesion」作爲從該文件讀取的輸入。

但是,如果該文件存在:然後檢查是否有輸入讀取

讀取整個文件或進一步行,你應該把在(可以用新的文件(FILENAME.EXT).exists()檢查)環(你實際上只讀一行)

while(sc.hasnextLine()) 
{ 
line=sc.nextLine() //check it first and then process 
//process this line for words 

}

+0

以及它的讀取文件的第一行,hwich是一個int,而不是第二行 – XcutionX

+0

我希望現在能夠運作? – Dineshkumar

+0

...仍然沒有工作..不知道爲什麼它沒有正確讀取文件... – XcutionX