[英]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.