Three methods for loading files in Java

Source: Internet
Author: User
Java Loads files in three ways. Generally, we load files in the following three ways, today, I want to write a wiki page to record it. To sum up, 1. Use the Class Loader
This method uses the Java class loader to load files. The root directory is the packaged root directory of the Java class. The relative directory is the package location of the current class. If the file you want to load is saved in the directory accessible by the class loader, this loading method is recommended (for security reasons, files under Web-INF in Web applications cannot be loaded through web-INF)
Java code
Inputstream = This. getclass (). getclassloader (). getresourceasstream (filepath); 2, loaded through the file system
This method is to load data through the system's file system mechanism. The parameter (file path) it accepts is an absolute path address, you may think that the file path will be hard coding in the code, not elegant. Of course, you can choose to obtain the project path in many ways and then assemble the corresponding relative path, at least I did.
Java code
Inputstream = new fileinputstream (File); but there is an important issue that needs to be explained. refer to the following example (on the WebLogic application server ):
Log4j is used as the log output tool, and the configuration file log4j. propertes of log4j is placed in the defaultwebapp \ WEB-INF directory. Log4j initializes through an automatically loaded servlet. The initialization code is as follows:

Java code
Servletcontext context = getservletcontext ();
Org. Apache. log4j. propertyconfigurator.
Configure (context. getrealpath ("/")
+ "/WEB-INF/log4j. properties "); where, context. getrealpath ("/") to obtain the real root directory of the current web application. For example, if your WebLogic is installed in D: \ Bea, the context is displayed in windows. getrealpath ("/") usually returns: D: \ Bea \ wlserver6.1 \ config \ mydomain \ applications \ defaultwebapp. In this way, the real path of the log4j. properties file is obtained after splicing with "/WEB-INF/log4j. properties. Now everything is normal! After the test is passed, all the files under defaultwebapp are converted into a. War package. during deployment, the system report cannot find "D: \ Bea ".
\ Wlserver6.1 \ null \ WEB-INF \ log4j. properties file! If your application needs to read other files that have been packaged into the war package, it will report that the files cannot be found. In addition, the system does not search for it in the D: \ Bea \ wlserver6.1 \ config \ mydomain \ applications \ defaultwebapp directory, but in the D: \ Bea \ wlserver6.1 \ null directory. This is because context. getrealpath ("/") returns NULL.
Check the API documentation of servletcontext. Originally, for a packaged application, there is no realpath concept. Calling getrealpath will only return null. In fact, it is easy to understand that a file is packaged. war file, there is no directory structure (although the directory structure still exists in the package, this is not the same as the directory structure in the file system ). Therefore, resources in the war package cannot obtain the realpath. In this way, the file IO cannot be read. So how do I read Resources in the war package? The answer is to use the servletcontext. getresourceasstream (string) method. Now, the war application can run successfully. But if you do not deploy the application through war, will the application be deployed directly through the directory structure fail to find the resource again? Please refer
Servletcontext. getresourceasstream API documentation,
Java code
# Returns a URL to the resource that is
# Mapped to a specified path. The path
# Must begin with a "/" and is interpreted
# As relative to the current context root.
# This method allows the servlet container
# To make a resource available to servlets
# From any source. resources can be located
# On a local or remote file system,
# In a database, or in a. War file.
# It can be seen that getresourceasstream can be used to obtain resources including the local file system, remote file system, war package, and so on. The above issues will not occur.
Conclusion: when developing J2EE Web applications, if you need to read files in this application, use servletcontext. getresourceasstream instead of file I/O. Getrealpath gets different parameters in different servers, some return NULL, and some return normal data, which depends on whether the server unpacks the file, in addition, in some servers, getrealpath ends with "/". It is best to make a judgment:
Java code
Realpath. endswith ("/")? Realpath :( realpath + "/")
3. web programs can be loaded through servletcontext.
The URL of a specific resource can be called by calling servletcontext. getresource (string path) is obtained. The path parameter must start with "/" and be parsed as the relative path of the root of the current servlet background. This method is different from the java. Lang. Class. getresource method based on the class loader. If you request a. jsp page through the servletcontext. getresource method, you will get the JSP Source Code. To get the execution result, you can use the include method of the requestdispatcher object. You can also directly obtain resources in the form of input streams,
  
Java code
Public inputstream getresourceasstream (string path); in the previous example, I/O is used to compare two objects. Java code
Inputstream = SC. getresourceasstream (enumconstants. server_configuration_filepath.tostring ());
/**
* "Server_configuration_filepath" server configuration reflection class properties file path <B> "/config/server-config.properites"
*/
Public static final enumconstants server_configuration_filepath = new enumconstants ("/config/server-config.properites"); from: http://www.360doc.com/content/11/0314/10/3477798_100936997.shtml

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.