Java 使用FileReader找不到文件
我正在为我的班级做一个项目,我们应该读入一个名为sampleSearch.txt的文件,下面是我正在使用的代码。问题是,通过eclipse,我似乎无法实际加载文件。即使文本文件与代码的其余部分位于同一目录中,它也总是显示“未找到文件”Java 使用FileReader找不到文件,java,filereader,Java,Filereader,我正在为我的班级做一个项目,我们应该读入一个名为sampleSearch.txt的文件,下面是我正在使用的代码。问题是,通过eclipse,我似乎无法实际加载文件。即使文本文件与代码的其余部分位于同一目录中,它也总是显示“未找到文件” import java.util.*; import java.io.*; public class Driver{ public static void main (String[] args){ // try block ne
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");
}
}
import java.util.*;
导入java.io.*;
公共类驱动程序{
公共静态void main(字符串[]args){
//尝试读取文件所需的块
尝试
{
//打开文件“sampleSearch.txt”
FileReader fileName=新的FileReader(“sampleSearch.txt”);
Scanner fileRead=新扫描仪(文件名);
//读取行数
int numRow=fileRead.nextInt();
fileRead.nextLine();
//读取列数
int numCol=fileRead.nextInt();
fileRead.nextLine();
//创建二维数组以保存文件中的字符
char[][]数组=新字符[numRow][numCol];
//对于文件中的每一行
对于(int r=0;r
}您需要知道代码在哪个目录中搜索文件: 这样做: 获取当前路径:
System.out.println(新文件(“.”.getAbsoluteFile())代码>
这将向您显示java代码查找文件的路径。使用从此位置开始的相对路径引用文件。干杯文件存储在哪里?您是否在同一执行上下文(即某个目录)中运行程序?该文件存储在eclipseUnderstand创建的同一目录(lab5/src/lab5)中,您的src
目录的内容并不构成程序的执行位置,在大多数情况下将被放入Jar文件中。尝试将文件移动到lab5
目录,位于src
目录上方,而不是运行正常的目录。非常感谢你。它位于目录中,比需要的位置低了一个文件夹。