search
HomeJavajavaTutorialHow to read properties configuration file in java

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!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How does the JVM manage garbage collection across different platforms?How does the JVM manage garbage collection across different platforms?Apr 28, 2025 am 12:23 AM

JVMmanagesgarbagecollectionacrossplatformseffectivelybyusingagenerationalapproachandadaptingtoOSandhardwaredifferences.ItemploysvariouscollectorslikeSerial,Parallel,CMS,andG1,eachsuitedfordifferentscenarios.Performancecanbetunedwithflagslike-XX:NewRa

Why can Java code run on different operating systems without modification?Why can Java code run on different operating systems without modification?Apr 28, 2025 am 12:14 AM

Java code can run on different operating systems without modification, because Java's "write once, run everywhere" philosophy is implemented by Java virtual machine (JVM). As the intermediary between the compiled Java bytecode and the operating system, the JVM translates the bytecode into specific machine instructions to ensure that the program can run independently on any platform with JVM installed.

Describe the process of compiling and executing a Java program, highlighting platform independence.Describe the process of compiling and executing a Java program, highlighting platform independence.Apr 28, 2025 am 12:08 AM

The compilation and execution of Java programs achieve platform independence through bytecode and JVM. 1) Write Java source code and compile it into bytecode. 2) Use JVM to execute bytecode on any platform to ensure the code runs across platforms.

How does the underlying hardware architecture affect Java's performance?How does the underlying hardware architecture affect Java's performance?Apr 28, 2025 am 12:05 AM

Java performance is closely related to hardware architecture, and understanding this relationship can significantly improve programming capabilities. 1) The JVM converts Java bytecode into machine instructions through JIT compilation, which is affected by the CPU architecture. 2) Memory management and garbage collection are affected by RAM and memory bus speed. 3) Cache and branch prediction optimize Java code execution. 4) Multi-threading and parallel processing improve performance on multi-core systems.

Explain why native libraries can break Java's platform independence.Explain why native libraries can break Java's platform independence.Apr 28, 2025 am 12:02 AM

Using native libraries will destroy Java's platform independence, because these libraries need to be compiled separately for each operating system. 1) The native library interacts with Java through JNI, providing functions that cannot be directly implemented by Java. 2) Using native libraries increases project complexity and requires managing library files for different platforms. 3) Although native libraries can improve performance, they should be used with caution and conducted cross-platform testing.

How does the JVM handle differences in operating system APIs?How does the JVM handle differences in operating system APIs?Apr 27, 2025 am 12:18 AM

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.

How does the modularity introduced in Java 9 impact platform independence?How does the modularity introduced in Java 9 impact platform independence?Apr 27, 2025 am 12:15 AM

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

What is bytecode, and how does it relate to Java's platform independence?What is bytecode, and how does it relate to Java's platform independence?Apr 27, 2025 am 12:06 AM

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

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor