加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 无法使用FileReader查找文件

发布时间:2020-12-15 05:11:32 所属栏目:Java 来源:网络整理
导读:我正在为我的课程开发一个项目,我们应该读一个名为sampleSearch.txt的文件,下面是我正在使用的代码.问题是通过 eclipse我似乎无法真正加载文件.即使文本文件与其余代码位于同一目录中,它总是会出现File Not Found. import java.util.*; import java.io.*; pu
我正在为我的课程开发一个项目,我们应该读一个名为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");
    }

}

}

解决方法

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

做这个:

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读