Path for image file in Eclipse src folder, on a Mac

天大地大妈咪最大 提交于 2019-12-13 04:30:02

问题


I'm trying to load an image file.

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. Should I put RCar.gif in the src or bin folder of an eclipse project?
  2. How would I refer to it without the explicit path? (I'm using a mac. I believe it should be something like ~/RCar.gif but am having trouble finding the correct syntax online.

Thanks!


回答1:


If you want to use relative paths, they are going to be relative to the project's root, or when its deployed, the directory that the jar file resides in. You can use src/RCar.gif as your filename.

It would be better if you created a separate folder for resources, then address them with new File("res/RCar.gif"); Another option is to put them in the src folder and address them using the classloader.




回答2:


If I recall correctly, Eclipse requires all resources to be placed in the resources directory. These will be automatically bundled with your application when you export it.

At runtime, you would simply use Class#getResource("/path/to/your/resource") where the path is the location from the "resource" folder




回答3:


You can load the icon quite easily when it is in the resource folder of the class it belongs to at runtime. See http://docs.oracle.com/javase/7/docs/api/java/lang/Class.html#getResource%28java.lang.String%29

Within the class your.packagename.YourClassName you could write the following:

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

The urlString would be /your/packagename/YourClassName/RCar.gif. Of course this is also where icon should be at runtime.

HTH




回答4:


yes...it takes the relative path.

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



来源:https://stackoverflow.com/questions/17398533/path-for-image-file-in-eclipse-src-folder-on-a-mac

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!