The example of this article describes the method of java reading the properties configuration file. Share it with everyone for your reference. The specific analysis is as follows:
In the past two days, I have been working on java projects and used property files. I searched the Internet for information. For a long time, I could not find a satisfactory method that allowed me to read the property values in the .properties file. It was very difficult. It’s depressing. There are roughly the following methods for obtaining attribute values on the Internet. The following three methods are gradually optimized to achieve the best results. The following uses the date.properties file as an example. The file is placed in the src directory. The file content is:
startdate=2011-02-07
totalweek=25
Method 1:
public class Stweek { static private String startdate = null; static private String totalweek = null; synchronized static public void loads(){ if(startdate == null || totalweek == null) { FileInputStream is = null; Properties dbProps = new Properties(); try { is = new FileInputStream(filepath); dbProps.load(is); startdate = dbProps.getProperty("startdate"); totalweek = dbProps.getProperty("totalweek"); } catch (Exception e) { System.err.println("不能读取属性文件. " + "请确保db.properties在CLASSPATH指定的路径中"); } } } public static String getStartdate() { if(tartdate==null) loads(); return startdate; } public static String getTotalweek() { if(startdate==null) loads(); return totalweek; } }
Although the above method can also obtain the configuration file content, its biggest problem is The positioning of the file path (that is, the filepath value problem in the code), when using absolute positioning, if you move the project to another drive letter to run, you need to modify the source code, otherwise an error will be reported, but if you use a relative path , when the Stweek class is moved to another package, the source code still needs to be modified, otherwise an error will be reported, so this method is too limited and not good. The following method 2 can solve this problem, but it still has some problems
Method 2:
public class Stweek { InputStream is = null; Properties dbProps = null; public Stweek() { // TODO Auto-generated constructor stub is = getClass().getResourceAsStream("/date.properties"); dbProps = new Properties(); try { dbProps.load(is); } catch (Exception e) { System.err.println("不能读取属性文件. " + "请确保db.properties在CLASSPATH指定的路径中"); } } public String getStartdate() { String sd = null; sd = dbProps.getProperty("startdate"); return sd; } public String getTotalweek() { String totalweek=null; totalweek = dbProps.getProperty("totalweek"); return totalweek; } }
The advantage of this method is that you don’t need to point out the absolute path of the configuration file, and whether you put the Stweek class into another package or move the entire project to another drive letter , the code can still run normally, and there will be no problem of not finding the file. However, this method still has a major flaw, because we often hope that the configuration file can be cached in memory, so that we do not have to access the hard disk every time it is read. (Accessing external memory is too time-consuming). For this reason, we hope to use static variables and static methods to cache and obtain variables, and at the same time be able to dynamically load these values. Then the problem arises, because getClass().getResourceAsStream(" /date.properties"); This sentence can only appear in the constructor (you can test it yourself). This method cannot be used in dynamic load. What should I do? Let’s look at the third method
Method three:
import java.io.InputStream; import java.util.Properties; public class Stweek { static private String startdate = null; static private String totalweek = null; static{ loads(); } synchronized static public void loads(){ if(startdate == null || totalweek == null) { InputStream is = Stweek.class.getResourceAsStream("/date.properties"); Properties dbProps = new Properties(); try { dbProps.load(is); startdate = dbProps.getProperty("startdate"); totalweek = dbProps.getProperty("totalweek"); } catch (Exception e) { System.err.println("不能读取属性文件. " + "请确保db.properties在CLASSPATH指定的路径中"); } } } public static String getStartdate() { if(startdate==null) loads(); return startdate; } public static String getTotalweek() { if(startdate==null) loads(); return totalweek; } }
This method can not only cache the contents of the configuration file, but also automatically load the contents of the configuration file into the memory. The user does not need to consider the manual loading process at all, and only needs to use it where it is needed. Just call Stweek.getStartdate() directly (because it is a static method, you don’t even need to create the object in advance). In this way, if there is a cache in the memory, the function will directly read the data in the memory, saving time. If there is no cache, Don't worry, the system will automatically load it for you. Users don't need to know how it is implemented. They only need to know that I can directly call the function to get the desired value.
I hope this article will help everyone's Java Programming helps.
For more articles on how to read properties configuration files in Java, please pay attention to the PHP Chinese website!

JVM handles operating system API differences through JavaNativeInterface (JNI) and Java standard library: 1. JNI allows Java code to call local code and directly interact with the operating system API. 2. The Java standard library provides a unified API, which is internally mapped to different operating system APIs to ensure that the code runs across platforms.

modularitydoesnotdirectlyaffectJava'splatformindependence.Java'splatformindependenceismaintainedbytheJVM,butmodularityinfluencesapplicationstructureandmanagement,indirectlyimpactingplatformindependence.1)Deploymentanddistributionbecomemoreefficientwi

BytecodeinJavaistheintermediaterepresentationthatenablesplatformindependence.1)Javacodeiscompiledintobytecodestoredin.classfiles.2)TheJVMinterpretsorcompilesthisbytecodeintomachinecodeatruntime,allowingthesamebytecodetorunonanydevicewithaJVM,thusfulf

JavaachievesplatformindependencethroughtheJavaVirtualMachine(JVM),whichexecutesbytecodeonanydevicewithaJVM.1)Javacodeiscompiledintobytecode.2)TheJVMinterpretsandexecutesthisbytecodeintomachine-specificinstructions,allowingthesamecodetorunondifferentp

Platform independence in JavaGUI development faces challenges, but can be dealt with by using Swing, JavaFX, unifying appearance, performance optimization, third-party libraries and cross-platform testing. JavaGUI development relies on AWT and Swing, which aims to provide cross-platform consistency, but the actual effect varies from operating system to operating system. Solutions include: 1) using Swing and JavaFX as GUI toolkits; 2) Unify the appearance through UIManager.setLookAndFeel(); 3) Optimize performance to suit different platforms; 4) using third-party libraries such as ApachePivot or SWT; 5) conduct cross-platform testing to ensure consistency.

Javadevelopmentisnotentirelyplatform-independentduetoseveralfactors.1)JVMvariationsaffectperformanceandbehavioracrossdifferentOS.2)NativelibrariesviaJNIintroduceplatform-specificissues.3)Filepathsandsystempropertiesdifferbetweenplatforms.4)GUIapplica

Java code will have performance differences when running on different platforms. 1) The implementation and optimization strategies of JVM are different, such as OracleJDK and OpenJDK. 2) The characteristics of the operating system, such as memory management and thread scheduling, will also affect performance. 3) Performance can be improved by selecting the appropriate JVM, adjusting JVM parameters and code optimization.

Java'splatformindependencehaslimitationsincludingperformanceoverhead,versioncompatibilityissues,challengeswithnativelibraryintegration,platform-specificfeatures,andJVMinstallation/maintenance.Thesefactorscomplicatethe"writeonce,runanywhere"


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment
