【问题标题】:I've been struggling with figuring out how to properly path my file input. I'm using Eclipse我一直在努力弄清楚如何正确路径我的文件输入。我正在使用 Eclipse
【发布时间】:2016-04-05 00:41:06
【问题描述】:

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

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

    BufferedReader parseText = new BufferedReader(parseFile);

【问题讨论】:

    标签: java eclipse file-io bufferedreader


    【解决方案1】:

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

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

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

    如果您打算使用它来解析学生成绩,我建议不要完全使用 FileReader 或 BufferedReader。 NIO 有一个readAllLines(URI); 函数,它返回一个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对象。

    希望这能回答你的问题!

    【讨论】:

      【解决方案2】:

      嘿,罗比,我不是专家,但请告诉我这是否可行

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

      如果您没有注意到 XD,您还可以将字符串路径注释掉。 祝你好运!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-05-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-11-08
        • 2021-05-29
        • 1970-01-01
        • 2023-02-14
        相关资源
        最近更新 更多