Can't Access Resources In Executable Jar
Others are correct with the use of getResourceAsStream
, but the path is a little tricky. You see the little package icon in the resources
folder? That signifies that all the files in the resource
folder will be put into the root of the classpath. Just like all the packages in src/main/java
are put in the root. So you would take out the resources
from the path
InputStream is = getClass().getResourceAsStream("/Cloudy_Day.png");
An aside: Maven has a file structure conventions. Class path resources are usually put into src/main/resources
. If you create a resources
dir in the src/main
, Eclipse should automatically pick it up, and create the little package icon for a path src/main/resource
that you should see in the project explorer. These files would also go to the root and could be accessed the same way. I would fix the file structure to follow this convention.
Note: A (As suggested by Bill Shannon, this is incorrect). As mentioned in his comment belowMimeBodyPart
, can be Constructed from an InputStream
"You can also attach the data using"
mbp.setDataHandler(new DataHandler(new ByteArrayDataSource(
this.getClass().getResourceAsStream("/Cloudy_Day.png", "image/png"))));
You can't access resources inside a JAR file as a File, only read them as an InputStream: getResourceAsStream()
.
As the MimeBodyPart has no attach()
method for an InputStream, the easiest way should be to read your resources and write them to temp files, then attach these files.