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