java - 无法使用 FileReader 找到文件

标签 java filereader

我正在为我的类(class)做一个项目,我们应该读取一个名为 sampleSearch.txt 的文件,下面包含我正在使用的代码。问题是,通过 eclipse 我似乎无法真正加载文件。即使文本文件与其余代码位于同一目录中,它也总是出现“未找到文件”。

 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");
    }

}    

最佳答案

您需要知道代码在哪个目录中搜索文件:

这样做:

获取当前路径:System.out.println(new File(".").getAbsoluteFile());

这将向您显示 java 代码查找文件的路径。使用从此位置开始的相对路径引用您的文件。干杯

关于java - 无法使用 FileReader 找到文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22902995/

相关文章:

java - 在Java中调用前一个switch

java - 转换为可运行 Jar 文件时读取 .ini 文件

HTML5 FileReader API 在将大文件读取为切片时导致 chrome 17 崩溃

Javascript解析文本数据错误?

java - 类型 'org/springframework/http/MediaType'(当前帧,堆栈 [1])不可分配给 'org/springframework/util/MimeType'

java - 在 Java 中使用 RegEx 接受带有单点的文件名

java - 卸载/安装 JDK

java - 将 PDF 转换为 HTML 文件 Java API

javascript - 为什么这个 FileReader onload 没有触发?

javascript - fileReader.readAsText() 抛出 'FileReader' : parameter 1 is not of type 'Blob'