Java read Jar package resource file

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.