2013-10-09 63 views
0

我們還沒有學會如何讀寫文件,但是我們已經提供了一個預設的方法來讀取一個txt文件。問題在於它似乎不起作用。這是給我們的預製方法。用Java讀取文件

/****************************************************************************** 
* 
* Filename :  GradeCalculatorFromFile.java. 
* Author:  xxxxxxxxxxx 
* Date:   09/025/2011 
* Description: This program computes the scores of a list of students in the CSE155a class 
* 
******************************************************************************/ 
import java.io.File; 
import java.io.FileNotFoundException; 
import java.util.*; 

/* Provide a description of the class */ 
public class GradeCalculatorFromFile { 
    public static void main(String[] args) { 
     // Declare and initialise the variables as needed 
     /* The following code enables the user to accept input from the keyboard. Keep this code as it is. */ 
     Scanner scanner = null; 
     try { 
      scanner = new Scanner(new File("grades.txt")); 
     } catch (FileNotFoundException e) { 
      System.out.println("Error opening file. Please make sure that you have a grades.txt file in the same folder as GradeCalculator.class"); 
      System.exit(0); 
     } 
     /* 
     Add your code here to read the number of students and the scores 
     Use scanner.next() to read a String 
     Use scanner.nextInt() to read an int 
     */ 
    } 
} 

現在,說明會告訴我們將grades.txt放在GradeCalculatorFromFile.class所在的文件夾中。我這樣做,但是我收到錯誤信息「Error opening file。請確保在GradeCalculator.class文件夾中有一個grades.txt文件」。該方法有問題嗎?我使用eclipse,並將grades.txt文件放在C:\ Users \ xxxx \ workspace \ Homework 3 \ bin

+1

Google如何獲取程序的當前路徑作爲字符串。然後輸出路徑,這應該給你一個你需要放置文件的地方的參考。 –

+0

不要粘貼它斌..將其移動到您的項目的根目錄。 else提供完整的路徑 –

+0

從我記得在Eclipse中你需要在項目級目錄而不是bin子目錄中調整資源。 – Pshemo

回答

2

Eclipse將工作目錄設置爲項目目錄。文件放到

C:\用戶\ XXXX \工作區\作業3

,它應該工作的罰款。

2

這可能是Eclipse從一個不同於你認爲它的工作目錄運行程序。嘗試從命令行通過cding運行程序到合適的目錄並運行「java GradeCalculator.class」

這應該有效。

1

嘗試將其移動到Homework 3目錄中。如果您正在使用javacjava命令來編譯和運行您的程序,那麼共同定位grades.txt文件和編譯後的類文件是正確的。然而,Eclipse會將類路徑修改爲非默認值。

1

您必須將文件放在你的src的根路徑,然後使用「/grades.txt」

0

你有兩個選擇閱讀:要麼,將文件移動到您的項目目錄

C:\Users\xxxx\workspace\Homework 3\ 

因爲這是Eclipse將其當前工作目錄設置爲。

你的第二個選項是打開該文件作爲資源流

Scanner scanner = null; 
scanner = new Scanner(
       GradeCalculatorFromFile.class.getResourceAsStream("grades.txt")); 

這是假設你的文件存在旁邊的GradeCalculatorFromFile.class(就像它已經是現在),即適用於您的CLASSPATH