2014-04-22 96 views
1

我在編碼java方面很新,而且我遇到了很多困難。 我想編寫一個程序使用bufferedreader從文件中讀取,我已經創建了名爲「scores.txt」。 所以我有一個名爲processFile的方法,它假設設置BufferedReader並循環遍歷文件,讀取每個分數。然後,我需要將分數轉換爲整數,將它們相加,並顯示計算出的平均值。java FileInputStream找不到文件

我不知道如何添加它們並計算平均值,但我目前正在從文件中讀取數據。 它一直說它不能罰款的文件,但我知道我的文件中有一個名爲「scores.txt」的文件。

這是我到目前爲止......這是非常糟糕的。我只是沒那麼這個:(好也許有一個不同的問題?

public static void main(String[] args) throws IOException, 
     FileNotFoundException { 

String file = "scores.txt"; 
processFile("scores.txt"); 
//calls method processFile 
} 


public static void processFile (String file) 
throws IOException, FileNotFoundException{ 
String line; 
//lines is declared as a string 


    BufferedReader inputReader = 
      new BufferedReader (new InputStreamReader 
    (new FileInputStream(file))); 

    while ((line = inputReader.readLine()) != null){ 
    System.out.println(line); 

    }  
    inputReader.close(); 
    } 
+0

使用'Files.newBufferedReader()'入手 - 也是一個嘗試,與資源聲明 – fge

+0

你缺少的文件路徑。現在你只有文件的名字。 –

回答

1

有可用的

  1. 使用絕對路徑主要有兩個選項文件(從Windows中的驅動器盤符開始或在* .nix中以 斜槓開始)。 「僅用於測試」任務非常方便。

    樣品 窗口 - d:/someFolder/scores.txt, * .nix - /someFolder/scores.txt

  2. 認沽文件到項目根目錄,在這種情況下,它會可見的 類加載器。

+0

謝謝!它現在工作:) – user3558440

0

將在項目文件夾的根目錄scores.txt,或者把完整的文件路徑中String file

程序不知道要檢查你的我的文檔文件夾scores.txt

+0

謝謝!我得到它的工作:) – user3558440

0

如果您使用的是IntelliJ,創建你的包一個input.txt的文件並右鍵單擊input.txt的文件,然後單擊copy path。您現在可以使用該路徑作爲輸入參數。

例子:

in = new FileInputStream("C:\\Users\\mda21185\\IdeaProjects\\TutorialsPointJava\\src\\com\\tutorialspoint\\java\\input.txt");