java - 用Java读取文件

标签 java eclipse file

我们还没有学习如何读取和写入文件,但是已经为我们提供了一个预制的方法,该方法应该读取 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 中

最佳答案

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

C:\Users\xxxx\workspace\Homework 3

它应该可以正常工作。

关于java - 用Java读取文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19278083/

相关文章:

php - 写入文件系统数据库中的现有文件

java - Android:如何永久保存变量?

java - 粗线防止变形

java - 为什么术语 "unit of work"如此重要,为什么 JDBC AutoCommit 违反了这个模式?

java - Selenium Chrome 驱动程序选择证书弹出确认不起作用

android - 在 Eclipse MAT 中,类(class)末尾的美元符号是什么意思?

eclipse - 排除 Eclipse IDE 中与 JUnit 4 的集成测试

java - 在 Java 中编译一行而不是另一行

c++ - 编写 multimap fo 文件 Fast way c++

android - Android 中的蓝牙文件传输