从相对路径读取文件 [英] Reading a file from a relative path
问题描述
我试图通过提供像这样的相对路径来读取图像文件:
BufferedImage image;
image = fm.readMap(.. \\..\\\\resources\\5x5.png);
阅读:
public BufferedImage readMap(String path)
{
BufferedImage img = null;
尝试{
img = ImageIO.read(new File(path));
catch(IOException e){
System.out.println(Image not found。);
e.printStackTrace
}
return img;
$ / code $ / pre
代码的位置:
parent - > src - > externalsourcemanagement - > TestMapAnalysis.java
图片的位置:parent - > resources - > 5x5.png
提前致谢! 相对路径不相对于Source(.java)文件,它相对于类路径。如果你在src目录下的bin文件夹下有类,那么你的图像的相对路径是
$ $ p $ image = fm。 readMap( resources\\5x5.png);
I know this question has been asked like 1000 times before. I did tried all the solutions(How to read file from relative path in Java project? java.io.File cannot find the path specified did not worked also), however none of them seems to be working.
I am trying to read a image file by providing a relative path like this:
BufferedImage image;
image = fm.readMap("..\\..\\resources\\5x5.png");
Reading:
public BufferedImage readMap(String path)
{
BufferedImage img = null;
try{
img = ImageIO.read(new File(path));
}
catch (IOException e){
System.out.println("Image not found.");
e.printStackTrace
}
return img;
}
location of the code :
parent --> src --> externalsourcemanagement --> TestMapAnalysis.java
location of the image : parent --> resources --> 5x5.png
Thanks in advance!
Relative path is not relative to the Source (.java) file, it is relative to the classpath. If you have classes under bin folder in the same directory as src, then your relative path of image would be
image = fm.readMap("resources\\5x5.png");
这篇关于从相对路径读取文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!