First, get the location of the jar Package 1. Using Classpath
String path = This.getclass (). Getprotectiondomain (). Getcodesource (). GetLocation (). GetPath ();
The return value is/xxx/xxx.jar this form. If the path contains Unicode characters, you also need to transcode the path
Path = Java.net.URLDecoder.decode (path, "UTF-8");
2. Using the Java runtime's system properties to get the jar file location is also/xxx/xxx.jar this form
String Path = System.getproperty ("Java.class.path"); int firstindex = Path.lastindexof (System.getproperty ("Path.separator")) + 1; int lastIndex = Path.lastindexof (file.separator) + 1; Path = path.substring (FirstIndex, LastIndex);
Path.separator is obtained under Windows system; (semicolon), under Linux: (colon). That is, the environment variable is commonly used to split the path of two symbols, such as in Windows we often set the environment variable path=xxxx\xxx;xxx\xxx; here is the semicolon.
File.separator is the/(slash) with \ (backslash), Windows is \ (backslash), Linux is/(slash).
Second, read the file in the JAR Package 1. Get the path to the file before loading the file resource
Java.net.URL FileURL = This.getclass (). GetResource ("/ui/image/background.jpg"); Javax.swing.Image backGround = new ImageIcon (FileURL). GetImage ();
2. Load the object directly
InputStream in = This.getclass (). getResourceAsStream ("/ui/image/background.txt");
Third, the JAR package program Operation 1.java
Java -classpath f:/testhello.jar Test2 or JAVA-CP f:/testhello.jar Test2
2.scala
Scala -classpath F:/testhello.jar Test2
Scala/java read files in project