简体   繁体   English

Java从项目和.jar中的相对路径读取文件

[英]java read file from relative path in project and .jar

I tried that: 我尝试过:

public class FilePath {

    public File return_path () {

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

If I print it, the output is a path like this: "/media/dates/%20uni%c3%a0/Java/project%20java%20201/SearchInFiles/build/classes/searchinfiles/hello.txt" 如果我打印它,输出将是这样的路径:“ / media / dates /%20uni%c3%a0 / Java / project%20java%20201 / SearchInFiles / build / classes / searchinfiles / hello.txt”

I have created this method in order not to redefine everytime the path of the file that eventually a .jar will have to read. 我创建此方法是为了避免每次都重新定义最终.jar必须读取的文件路径。

There could be a problem with the strange characters? 奇怪的人物可能有问题吗?

Btw when I call it from main class: 顺便说一句,当我从主类中调用它时:

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());
        }
}

I have the "file not existing" error. 我有“文件不存在”错误。

How can I solve it? 我该如何解决? Thanks 谢谢

Your urls are escaped, this is useful for webbrowsers where you can't write spaces in urls for example and they get represented as "%20", or hex 20, or char 32 in ascii. 您的网址被转义了,这对于Web浏览器很有用,例如,您不能在网址中写空格,并且它们表示为“%20”,十六进制20或ascii的char 32。

What you want is to unescape this, the following post may help you 您想要的是对此进行转义, 以下文章可能会对您有所帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从Java中的项目根文件夹读取具有相对路径的文件? - How to read file with relative path from project root folder in Java? 如何从 Java 项目中的相对路径读取文件? java.io.文件找不到指定的路径 - How to read file from relative path in Java project? java.io.File cannot find the path specified 无法使用相对路径将文件从jar读取到FileInputStream中 - Unable to read a file from a jar into a FileInputStream using a relative path 使用相对路径将 jar 文件添加到 Eclipse 项目 - Add jar file to Eclipse project with relative path Java/JavaFX,从项目和 jar 文件中读取文件 - Java/JavaFX, read files from inside project and jar file Web项目内的jar所需文件的相对路径 - Relative path of a file needed by a jar inside a web project 如何在Netbeans项目中添加.jar文件并指定相对路径 - How to add a .jar file in a Netbeans project specifying a relative path 如何通过使用相对路径读取可执行jar外部的文本文件 - How to read a text file outside executable jar by using relative path 从类路径,绝对路径,包括“ ../ ..”路径的相对路径中读取Java中的文件 - Read a file in Java from classpath, absolute path, relative path that includes “../..” path 从Maven项目中的相对路径读取文件 - reading a file from a relative path in a maven project
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM