从相对路径读取文件 [英] Reading a file from a relative path

查看:153
本文介绍了从相对路径读取文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这个问题以前曾经有过1000次的要求。我曾尝试所有的解决方案(如何从Java项目中的相对路径读取文件?java.io.File找不到指定的路径也没有工作,但是他们似乎没有工作。



我试图通过提供像这样的相对路径来读取图像文件:

  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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆