【问题标题】:java read file from relative path in project and .jarjava从项目和.jar中的相对路径读取文件
【发布时间】:2013-05-09 20:43:02
【问题描述】:

我试过了:

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

我遇到“文件不存在”错误。

我该如何解决? 谢谢

【问题讨论】:

  • 看看右边类似的问题......
  • 为什么不直接使用getClass().getResourceAsStream(fileName)
  • 这个效果更好,谢谢

标签: java file jar relative-path


【解决方案1】:

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

你想要的是避免这种情况,following post 可能会帮助你

【讨论】:

    猜你喜欢
    • 2011-06-30
    • 2018-11-11
    • 1970-01-01
    • 2011-04-20
    • 2014-05-23
    • 1970-01-01
    • 2017-03-17
    相关资源
    最近更新 更多