简体   繁体   中英

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"

I have created this method in order not to redefine everytime the path of the file that eventually a .jar will have to read.

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.

What you want is to unescape this, the following post may help you

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM