无法使用FileReader查找文件

时间:2014-04-07 03:10:41

标签: java filereader

我正在为我的课程开发一个项目,我们应该读一个名为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");
    }

}    

}

1 个答案:

答案 0 :(得分:13)

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

这样做:

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

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