Package Java project into a jar package, if there is a resource file in the jar package needs to access, need to take the form of stream access, you can call the getResourceAsStream () method, and cannot be accessed by path (the file has been hit into the jar, Not conforming to the path). There are two ways to store using the getResourceAsStream () method file:
(1) The file is stored under the class path of SRC.
(2) The file is stored under the Resource folder, and the normal folder is changed to a resource folder through the build Path-use as Source folders.
, package the Testa into a jar package, import testb (build Path-add to build Path), and access TestA.txt and TestB.txt in Testb.
1 @Test2 Public voidTest () {3String line =NULL;4BufferedReader Bufferreader =NULL;5 Try {6InputStream InputStream = App.class. getResourceAsStream ("TestA.txt");7Bufferreader =NewBufferedReader (NewInputStreamReader (InputStream));8 while(line = Bufferreader.readline ())! =NULL) {9 System.out.println (line);Ten } One}Catch(Exception e) { A e.printstacktrace (); -}finally { - Try { the bufferreader.close (); -}Catch(IOException e) { - e.printstacktrace (); - } + } -}
To access Testb, change the Get InputStream statement to InputStream InputStream = App.class.getResourceAsStream ("/testb.txt"). For the Class.getresourceasstream () method, no "/" means looking under the current classpath, plus "/" to find from the root path of the classpath.
Alternatively, you can use the Classloader.getresourceasstream () method to find from the root path of the classpath, that is, whether or not the resource you are looking for is preceded by a "/" from the root path of the classpath.
Java read Jar package resource file