getresource () and getResourceAsStream ()
The compiled Java class file can be packaged as a jar file to run anywhere. But when we need to use some resources such as: an image, a piece of audio, you need to have a resource folder in the jar package, you must ensure that the jar package and the resource folder are released together or the program will not function properly. What we want is to publish only a jar package that includes all of the resources. To do this we need to read the resource file:
Take advantage of the two function URLs provided by Java Class.getResource () and InputStream Class.getresourceasstream ().
Only the function URL Class.getResource () is highlighted here, and the function InputStream Class.getresourceasstream () is similar to this.
My project structure is as follows:
The file version.properties is stored in the following location:
The code is as follows: Package Com.ryze.work.component;public class MainFrame {//public static final String Version_properties_filename = "/version.properties";p ublic static final String version_properties_filename = "Version.properties";p ublic static void Main (string[] args) throws exception{mainframe MainFrame = new MainFrame (); Mainframe.test ();} public void Test () {Java.net.URL versionpropertiesurl = This.getclass (). getresource (Version_properties_filename); System.out.println (Versionpropertiesurl);}}
The results of the operation are as follows:
When using the code public static final string version_properties_filename = "/version.properties"; replace public static final string Version_properties_filename = "Version.properties";
You need to put the file version.properties to the following path:
Java Learning---getresource () and getResourceAsStream ()