【问题标题】:Cant find file using FileReader使用 FileReader 找不到文件
【发布时间】: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


【解决方案1】:

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

这样做:

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

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

【讨论】:

  • 效果很好。非常感谢你。它位于目录下一个文件夹中,比需要的位置低一个文件夹。
猜你喜欢
  • 2021-08-30
  • 2014-03-05
  • 1970-01-01
  • 2014-04-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多