【问题标题】:In java BufferedReader doesn't find a file, even when file exists (and it's existance is confirmed using java)!在 java BufferedReader 中找不到文件,即使文件存在(并且使用 java 确认了它的存在)!
【发布时间】:2018-12-18 19:25:30
【问题描述】:

我正在尝试使用BufferedReader 来读取文件的行,但它给了我FileNotFoundException。经过一番搜索,我找到了一种检查文件是否存在的方法(我使用了这个:https://www.javabrahman.com/quick-tips/how-to-check-for-existence-of-a-file-in-java/)。它返回 true,因此文件确实存在,并且路径正确,但是 BufferedReader 仍然找不到它。我查看了一堆可能的解决方案,但似乎没有一个有效。 这是我的代码:

import java.io.*;
import java.lang.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class neki
{
    public static void main(String[] args)
    {
        File file = new File("C:\\Users\\natan\\Desktop\\words.txt");
        BufferedReader br = new BufferedReader(new FileReader(file));
        String curr="AAAAAA";
        int st=11184810;
        String word; 
        boolean digit=false;
        while(!curr.equals("ffffff"))
        {
            curr=Integer.toHexString(st);
            for(int i=0;i<6;i++)
            {
                char c=curr.charAt(i);
                if(Character.isDigit(c))
                {
                    digit=true;
                }
            }
            if(!digit)
            {
                for(int j=0;j<466545;j++)
                    {
                        word=br.readLine();
                        word=word.toLowerCase();
                        if(curr==word)
                        {
                            System.out.println(curr);
                        }
                    }
            }
            st++;
            digit=false;
            Path filePath_1= Paths.get("C:\\Users\\natan\\Desktop\\words.txt");
            boolean fileExists_1= Files.exists(filePath_1);
            System.out.println("File 'bleh' exists: "+fileExists_1);

        }
    }
} 

【问题讨论】:

  • 您是否尝试在将 fileexists() 方法传递给 FileInputStream 之前调用它?
  • 我怀疑您使用 File 为一种方法获取文件,但使用 Paths 为另一种方法获取文件。不能说我对这两个都太熟悉了,但似乎它们的工作方式不太一样。
  • @obermillerk 不要认为这是给定的(它有点复杂),但它们是可以互换的。这应该不是问题。虽然,我也强烈建议使用 Paths-API 而不是 File-API。
  • 检查父文件夹stackoverflow.com/questions/21008976/…的权限

标签: java


【解决方案1】:

这些路径不一样,一个路径中有'test\',另一个没有。

new File("C:\\Users\\natan\\Desktop\\test\\words.txt"); Paths.get("C:\\Users\\natan\\Desktop\\words.txt");

使用常量来保存在多个地方引用的静态值可以防止这种错误。

【讨论】:

  • 您好,谢谢您的回答。不幸的是,文件路径的差异最初并不存在,我添加了它,因为我试图解决问题并忘记在问题中将其更改回来。很抱歉造成混乱!
  • @Natanšemrl 这是否意味着这个答案是正确的,还是这个答案不合适?
  • 这不是一个合适的答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-10-08
  • 1970-01-01
  • 2018-12-30
  • 1970-01-01
  • 1970-01-01
  • 2014-02-20
  • 2014-09-08
相关资源
最近更新 更多