Java reads the resource file instance program in the jar package

Source: Internet
Author: User

This article introduces the resource file program code used to read the jar package from java. XWork has a tool class called ClassLoaderUtil, we can thoroughly read the resource files in the jar package and use it to read the jar package.

1) ClassLoader is abstract, and objects cannot be instantiated. It is also impossible to call the above two methods through ClassLoader. Therefore, when writing code, we use the getResource () and getResourceAsStream () methods in the Class. These two methods will delegate the getResource () and getResourceAsStream () methods in the ClassLoader. Now let's re-write a Resource code to see what the above confusing words mean:

Java code

The Code is as follows: Copy code

Package edu. hxraid;
Import java. io .*;
Import java.net. URL;
Public class Resource {
Public void getResource () throws IOException {
// Search for the URL of the specified resource, in which the res.txt is still in the bin directory
URL fileURL = this. getClass (). getResource ("/resource/res.txt ");
System. out. println (fileURL. getFile ());
}
Public static void main (String [] args) throws IOException {
Resource res = new Resource ();
Res. getResource ();
}
}

(2) We can't read the resource file res.txt in resourcejar.jarby using the handler of the regular operation file, but we can use the getResourceAsStream () method of the Class to obtain the resource file. This method is transparent to us. We rewrite Resource. java:

Java code

The Code is as follows: Copy code

Package edu. hxraid;
Import java. io .*;
Public class Resource {
Public void getResource () throws IOException {
// Return the input stream for reading the specified resource
InputStream is = this. getClass (). getResourceAsStream ("/resource/res.txt ");
BufferedReader br = new BufferedReader (new InputStreamReader (is ));
String s = "";
While (s = br. readLine ())! = Null)
System. out. println (s );
}
}

Note:

Generally, after compiling a Java program, we can obtain the resource path. During the development and debugging period (before packaging), there is no problem. However, after packaging, because resources (images, configuration files, etc.) are packaged into jar files. if the dir attribute is changed, the resource file in the jar file cannot be found in the absolute path mode. When a program loads an image or text file, it uses the current working path as the benchmark to specify the file and path. After the resource file is stored in the jar package, the program cannot be found through the absolute path. Therefore, you can use Java's class-based path search method. You can use either of the following methods:

Obtain the root path relative to the package

 

The Code is as follows: Copy code

String path = new File (FrameConfig. class. getResource ("/"). getFile ())

. GetAbsolutePath ();

Get the stream relative to the package path

Reader reader = new InputStreamReader (

FrameConfig. class. getResourceAsStream ("/res/uiConfig. xml "));

The program containing this Code is based on the class (class path) at runtime, and does not depend on the current path (user. dir in System ),

[Note]: The above path "/res/uiConfig. xml is the path relative to the package. If it is written as "res/uiConfig. xml, indicating the path relative to the class: package/res/uiConfig. xml, which requires the Save path of the image and text files to be consistent with the path specified in the program.

[Note]: The above path "/res/uiConfig. xml is the path relative to the package. If it is written as "res/uiConfig. xml, indicating the path relative to the class: package/res/uiConfig. xml, which requires the Save path of the image and text files to be consistent with the path specified in the program.

Read the root Element (dom4j) in the jar package)

The Code is as follows: Copy code

Private static Element getRootElement (String path ){
Element rootElement = null;
Reader reader = null;
Try {
Reader = new InputStreamReader (
FrameConfig. class. getResourceAsStream (path ));
RootElement = new SAXReader (). read (reader). getRootElement ();
} Catch (Exception e ){
E. printStackTrace ();
} Finally {
CloseStream (reader );
}
Return rootElement;
}

Private static void closeStream (Closeable stream ){
If (stream! = Null)
Try {
Stream. close ();
} Catch (IOException e ){
E. printStackTrace ();
}
}

Public static void main (String [] args ){
Element uiConfig = getRootElement ("/res/uiConfig. xml ");
}


Read the root Element (jdom) in the jar package)

The Code is as follows: Copy code

Private static Element getRootElement (String path ){
Element rootElement = null;
Reader reader = null;
Try {
Reader = new InputStreamReader (
FrameConfig. class. getResourceAsStream (path ));
RootElement = new SAXBuilder (). build (reader). getRootElement ();
} Catch (Exception e ){
E. printStackTrace ();
} Finally {
CloseStream (reader );
}
Return rootElement;
}


Read international resource files in the jar package

The Code is as follows: Copy code

ResourceBundle resources = ResourceBundle. getBundle (
"Res. i18n", Locale. getDefault ());
// Obtain the corresponding value
String value = resources. getString (key );


Read image resources in the jar package

The Code is as follows: Copy code

Public static Image getImage (String imageName ){
InputStream inputStream = null;
ByteArrayOutputStream outputStream = null;
Try {
InputStream = FrameConfig. class. getResourceAsStream ("/res/images /"
+ ImageName );
OutputStream = new ByteArrayOutputStream ();
Byte buffer [] = new byte [1024];
Int len = 0;
While (len = inputStream. read (buffer ))! =-1)
OutputStream. write (buffer, 0, len );
Return Toolkit. getdefatooltoolkit (). createImage (
OutputStream. toByteArray ());
} Catch (Throwable th ){
Th. printStackTrace ();
} Finally {
CloseStream (inputStream );
CloseStream (outputStream );
}
Return null;
}

Public static void main (String [] args ){
Image image = getImage ("add.gif ");
}

Related Article

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.