0

我试过了:

public class FilePath {

    public File return_path () {

        URL url = getClass().getResource("file.txt"); 
        File file = new File(url.getPath()); 
        return file;
    }
}

如果我打印它,输出是这样的路径:“/media/dates/%20uni%c3%a0/Java/project%20java%20201/SearchInFiles/build/classes/searchinfiles/hello.txt”

我创建了这个方法是为了不每次都重新定义最终 .jar 必须读取的文件的路径。

奇怪的字符可能有问题?

顺便说一句,当我从主类调用它时:

public static void main(String[] args) {

        FilePath path = new FilePath(); 
        File file = path.return_path();
        System.out.println (file);

try{
BufferedReader input = new BufferedReader(new FileReader(file));

            String line;

    int i = 0;
    while ((line = input.readLine ()) != null)
    {
         System.out.println(line);
    }
            input.close();
        } 
        catch(Exception ex){
           System.err.println("Error: " + ex.getMessage());
        }
}

我有“文件不存在”错误。

我该如何解决?谢谢

4

1 回答 1

0

你的 url 被转义了,这对于你不能在 url 中写空格并且它们被表示为“%20”、十六进制 20 或 ascii 中的字符 32 的 web 浏览器很有用。

您想要的是避免这种情况,以下帖子可能会帮助您

于 2013-05-09T20:46:37.380 回答