我一直在努力弄清楚如何正确设置我的文件输入路径。我正在使用 Eclipse

I've been struggling with figuring out how to properly path my file input. I'm using Eclipse

例外是 java.io.FileNotFoundException。我尝试了多种方法,甚至尝试将其粘贴到几乎所有地方。我想我可以使用文件输入流,但我现在还是迷路了。我感谢任何解释。谢谢。这个程序的目标是解析一个包含学生姓名和成绩的文件,然后将它们组织成中位数、最好和最差的分数,同时将它们作为单独的文件输出。

    //String path = "C:/Users/Rob/Documents/";
    FileReader parseFile = new FileReader("input.txt");

    BufferedReader parseText = new BufferedReader(parseFile);

嘿罗比,我不是专家,但请告诉我这是否有效

FileReader parseFile = new FileReader("C:/Users/Rob/Documents/input.txt");

另外,如果您没有注意到 XD,您也将字符串路径注释掉了。 祝你好运!

如果您的文件始终位于同一位置,您可以使用上面的答案,但如果它放在不同的 OS(例如 Unix)上,/ 字符将无法按预期工作。因此,我会使用

FileReader parseFile = new FileReader(new File("input.txt").toAbsolutePath());

此代码假定 input.txt 与您的应用程序位于同一目录中。如果不是,你不能使用这个。

如果你打算用它来解析学生成绩,我建议不要一起使用 FileReader 或 BufferedReader。 NIO 有一个 readAllLines(URI); 函数,其中 returns 一个 List<String>:

List<String> lines = Files.readAllLines(new File("input.txt").toAbsoluteFile().toURI());

此代码仍会抛出 IOException,但它很容易完成工作,而且我发现它更易于使用。

或者,您可以调试可能抛出 IOexception 的原因,并使用 File API 阻止它们。例如:

public static String debugConnectionsToFile(File file) {
        if(!file.exists()){
            return "file does not exist!";
        }
        else if(!file.isFile()){
            return "File is not actually a file!";
        }
        else if(!file.canRead()){
            return "File cannot be read!";
        }

        else{
            try {
                FileReader reader = new FileReader(file);
                BufferedReader br = new BufferedReader(reader);
                try {
                    br.readLine();
                    br.close(); //It is true that this statement could cause an error, but it has never happened to me before.
                } catch (IOException e) {
                    return "File cannot be read by the reader!";
                }
            } catch (FileNotFoundException e) {
                return "File cannot be found or accessed by the reader";
            }
            return "It works fine!";
        }
    }

您可以使用构造函数File(String filepath)获得一个File对象。

希望这能回答您的问题!