【发布时间】:2023-03-08 17:03:02
【问题描述】:
我正在为我的班级开展一个项目,我们应该读取一个名为 sampleSearch.txt 的文件,其中包含我正在使用的代码。问题是通过 eclipse 我似乎无法实际加载文件。即使文本文件与其余代码位于同一目录中,它也总是出现 File Not Found。
import java.util.*;
import java.io.*;
public class Driver{
public static void main (String[] args){
// try block needed to read in file
try
{
//open the file "sampleSearch.txt"
FileReader fileName = new FileReader("sampleSearch.txt");
Scanner fileRead = new Scanner(fileName);
//read in the number of rows
int numRow = fileRead.nextInt();
fileRead.nextLine();
//read in the number of columns
int numCol = fileRead.nextInt();
fileRead.nextLine();
//create a 2d array to hold the characters in the file
char[][] array = new char[numRow][numCol];
//for each row in the file
for (int r = 0; r < numRow; r++)
{
//read in the row as a string
String row = fileRead.nextLine();
//parse the string into a sequence of characters
for (int c = 0; c < numCol; c++)
{
//store each character in the 2d array
array[r][c] = row.charAt(c);
}
}
//create a new instance of the WordSearch class
WordSearch ws = new WordSearch(array);
//play the game
ws.play();
}
catch (FileNotFoundException exception)
{
//error is thrown if file cannot be found. See directions or email me...
System.out.println("File Not Found gribble");
}
}
}
【问题讨论】:
-
文件存储在哪里?您是否在相同的执行上下文(即某个目录)中运行程序?
-
文件存放在eclipse创建的同一个目录(lab5/src/lab5)
-
要明白你的
src目录的内容并不构成程序的执行位置,大部分情况下会放到一个Jar文件中。尝试将文件移动到lab5目录,而不是src目录上方
标签: java filereader