【问题标题】:Path for image file in Eclipse src folder, on a MacEclipse src 文件夹中图像文件的路径,在 Mac 上
【发布时间】:2013-06-28 05:22:06
【问题描述】:

我正在尝试加载图像文件。

File imageCheck = new File("Users/me/Documents/workspace/ChineseChess/src/RCar.gif");
if (imageCheck.exists())
    System.out.println("Image file found!");
else
    System.out.println("Image file not found! :(");
button.setIcon(new ImageIcon("Users/me/Documents/workspace/ChineseChess/src/RCar.gif"));
  1. 我应该将 RCar.gif 放在 Eclipse 项目的 src 或 bin 文件夹中吗?
  2. 如果没有显式路径,我将如何引用它? (我使用的是 Mac。我认为它应该类似于 ~/RCar.gif,但在网上找不到正确的语法。

谢谢!

【问题讨论】:

    标签: java eclipse macos path


    【解决方案1】:

    是的...它采用相对路径。

    public static final String FILE_PATH = "src/test/resources/car.png";

    【讨论】:

      【解决方案2】:

      当图标在运行时它所属的类的资源文件夹中时,您可以很容易地加载图标。 见http://docs.oracle.com/javase/7/docs/api/java/lang/Class.html#getResource%28java.lang.String%29

      your.packagename.YourClassName 类中,您可以编写以下内容:

      String folderName = YourClassName.class.getName().replace('.', '/' );
      String urlString = "/"+folderName+"/RCar.gif";
      URL fileUri = YourClassName.class.getResource(urlString);
      button.setIcon(new ImageIcon(fileUri));
      

      urlString 将是/your/packagename/YourClassName/RCar.gif。当然这也是图标在运行时应该出现的地方。

      HTH

      【讨论】:

        【解决方案3】:

        如果您想使用相对路径,它们将相对于项目的根目录,或者在部署项目时,jar 文件所在的目录。您可以使用src/RCar.gif 作为文件名。

        如果您为资源创建一个单独的文件夹会更好,然后使用new File("res/RCar.gif"); 寻址它们另一个选择是将它们放在 src 文件夹中并使用类加载器对其进行寻址。

        【讨论】:

        • 修复了答案,它现在实际上使用相对路径:)
        【解决方案4】:

        如果我没记错的话,Eclipse 要求所有资源都放在资源目录中。这些将在您导出时自动与您的应用程序捆绑在一起。

        在运行时,您只需使用Class#getResource("/path/to/your/resource"),其中路径是“资源”文件夹中的位置

        【讨论】:

        • If I recall correctly, Eclipse requires all resources to be placed in the resources directory. 不是自动的。该文件夹必须位于 Eclipse 构建路径中。如果您不使用像 Apache Maven 这样的构建管理器,您可以右键单击文件夹并选择 Build Path / Use as Source Folder
        • @Sandro 从未使用过 Eclipse,但我记得很多人在将资源放入 src 文件夹时遇到问题。据我了解,Eclipse 有一个自动设置的“资源”文件夹
        • 嗯,Maven 文件夹结构的默认布局包含“资源”文件夹。有时项目未设置为自动构建。在这种情况下,资源不会复制到构成运行时资源的 Eclipse 输出文件夹中,因此在运行时不可用。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-08-06
        • 1970-01-01
        • 2012-04-29
        • 1970-01-01
        • 2014-02-12
        相关资源
        最近更新 更多