0

我们还没有学习如何读取和写入文件,但是我们已经提供了一个预制的方法,假设是读取一个 txt 文件。问题是它似乎不起作用。这是给我们的预制方法。

/******************************************************************************
 *
 * 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 相同的文件夹中。我这样做了,但我收到错误消息“打开文件时出错。请确保您在与 GradeCalculator.class 相同的文件夹中有一个 grades.txt 文件”。方法有问题吗?我正在使用eclipse,我将grades.txt文件放在C:\Users\xxxx\workspace\Homework 3\bin

4

5 回答 5

2

Eclipse 将工作目录设置为项目目录。把文件放到

C:\Users\xxxx\workspace\Homework 3

它应该可以正常工作。

于 2013-10-09T16:54:19.977 回答
2

可能是 Eclipse 从与您认为的不同的工作目录运行程序。尝试从命令行运行程序,方法是进入正确的目录并运行“java GradeCalculator.class”

那应该行得通。

于 2013-10-09T16:54:52.053 回答
1

尝试将其移动到Homework 3目录中。如果您使用javacandjava命令来编译和运行您的程序,那么将grades.txt 文件和已编译的类文件放在一起是正确的。然而,Eclipse 将类路径修改为非默认值。

于 2013-10-09T16:55:12.410 回答
1

您必须将文件放在 src 路径的根目录中,然后使用“/grades.txt”读取它

于 2013-10-09T16:55:54.620 回答
0

您有两个选择:或者,将文件移动到您的项目目录

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

因为这就是 Eclipse 将其当前工作目录设置为的内容。

您的第二个选择是将文件作为资源流打开

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

这假设您的文件存在于您的旁边GradeCalculatorFromFile.class(就像现在已经存在一样),即在您的CLASSPATH.

于 2013-10-09T17:00:05.323 回答