Reading .properties files in Java mainly uses the Properties class with FileInputStream or class loader. 1. Use FileInputStream to load local files: Create a Properties instance, and call the load() method to load the file contents through FileInputStream; 2. Read resources from classpath: Use getResourceAsStream() method, pay attention to the path writing method; 3. Handle Chinese garbled problems: Java 9 can specify encoding loading, Java 8 and below need to manually wrap InputStreamReader to specify encoding. In addition, attention should be paid to details such as paths, encodings and exception handling.
Reading .properties
files in Java is actually quite straightforward, the key is to use the right classes and methods. Java provides Properties
class that specifically handles this key-value pair format configuration file. As long as you master the basic usage, it will be very convenient to use it later.

Load local files using Properties class
The most common way is to load the local .properties
file through the Properties
class and FileInputStream
. This method is suitable for situations where the configuration file is in the project directory or the server's local path.
The operation steps are roughly as follows:

- Create a
Properties
instance - Read target
.properties
file usingFileInputStream
- Call
load()
method to load the file content into theProperties
object - Then you can get the corresponding value through
getProperty("key")
Sample code:
Properties prop = new Properties(); try (FileInputStream fis = new FileInputStream("config.properties")) { prop.load(fis); String dbUrl = prop.getProperty("database.url"); } catch (IOException e) { e.printStackTrace(); }
Note: Don't forget to close the flow. It is recommended to use try-with-resources to automatically manage resource release.

Read resource files from classpath
If your .properties
file is placed in the resources directory (such as Maven or Spring Boot project), you don't need to use absolute or relative paths, but should be loaded from the classpath through the classloader.
At this time, you can use ClassLoader.getSystemResourceAsStream()
or getClass().getResourceAsStream()
method of a certain class.
For example:
Properties prop = new Properties(); try (InputStream is = MyClass.class.getResourceAsStream("/config.properties")) { if (is != null) { prop.load(is); } else { System.out.println("Specified configuration file not found"); } }
Here you need to pay attention to the path writing:
- If it starts with
/
, it means that the search starts from the classpath root directory - Otherwise, it will be found from the package path where the current class is located.
Frameworks like Spring Boot usually place configuration files under src/main/resources
, which is particularly applicable.
Handle Chinese garbled problem
Sometimes you will find that the read value is garbled, especially when there is Chinese in the configuration file. This is because .properties
is ISO-8859-1 encoding by default, and the file you save may be UTF-8.
There are two solutions:
- Save the
.properties
file as ISO-8859-1 encoding and escape Chinese characters with native2ascii - Or manually specify the encoding format when loading (supported by Java 9)
Properties
after Java 9 have added a load(InputStream, Charset)
method, which can specify the encoding:
prop.load(new InputStreamReader(is, StandardCharsets.UTF_8));
If it is Java 8 and below, you need to wrap InputStreamReader
yourself and specify the encoding, which can also avoid garbled code.
Basically that's it. Reading the .properties
file itself is not complicated, but some details are easy to ignore, such as paths, encodings, exception handling, etc. As long as you notice these points, it will be easy to use.
The above is the detailed content of How to read a .properties file in Java?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

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

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

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

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

The difference between HashMap and Hashtable is mainly reflected in thread safety, null value support and performance. 1. In terms of thread safety, Hashtable is thread-safe, and its methods are mostly synchronous methods, while HashMap does not perform synchronization processing, which is not thread-safe; 2. In terms of null value support, HashMap allows one null key and multiple null values, while Hashtable does not allow null keys or values, otherwise a NullPointerException will be thrown; 3. In terms of performance, HashMap is more efficient because there is no synchronization mechanism, and Hashtable has a low locking performance for each operation. It is recommended to use ConcurrentHashMap instead.

Java uses wrapper classes because basic data types cannot directly participate in object-oriented operations, and object forms are often required in actual needs; 1. Collection classes can only store objects, such as Lists use automatic boxing to store numerical values; 2. Generics do not support basic types, and packaging classes must be used as type parameters; 3. Packaging classes can represent null values ??to distinguish unset or missing data; 4. Packaging classes provide practical methods such as string conversion to facilitate data parsing and processing, so in scenarios where these characteristics are needed, packaging classes are indispensable.

StaticmethodsininterfaceswereintroducedinJava8toallowutilityfunctionswithintheinterfaceitself.BeforeJava8,suchfunctionsrequiredseparatehelperclasses,leadingtodisorganizedcode.Now,staticmethodsprovidethreekeybenefits:1)theyenableutilitymethodsdirectly

The JIT compiler optimizes code through four methods: method inline, hot spot detection and compilation, type speculation and devirtualization, and redundant operation elimination. 1. Method inline reduces call overhead and inserts frequently called small methods directly into the call; 2. Hot spot detection and high-frequency code execution and centrally optimize it to save resources; 3. Type speculation collects runtime type information to achieve devirtualization calls, improving efficiency; 4. Redundant operations eliminate useless calculations and inspections based on operational data deletion, enhancing performance.

Instance initialization blocks are used in Java to run initialization logic when creating objects, which are executed before the constructor. It is suitable for scenarios where multiple constructors share initialization code, complex field initialization, or anonymous class initialization scenarios. Unlike static initialization blocks, it is executed every time it is instantiated, while static initialization blocks only run once when the class is loaded.

InJava,thefinalkeywordpreventsavariable’svaluefrombeingchangedafterassignment,butitsbehaviordiffersforprimitivesandobjectreferences.Forprimitivevariables,finalmakesthevalueconstant,asinfinalintMAX_SPEED=100;wherereassignmentcausesanerror.Forobjectref

Factory mode is used to encapsulate object creation logic, making the code more flexible, easy to maintain, and loosely coupled. The core answer is: by centrally managing object creation logic, hiding implementation details, and supporting the creation of multiple related objects. The specific description is as follows: the factory mode handes object creation to a special factory class or method for processing, avoiding the use of newClass() directly; it is suitable for scenarios where multiple types of related objects are created, creation logic may change, and implementation details need to be hidden; for example, in the payment processor, Stripe, PayPal and other instances are created through factories; its implementation includes the object returned by the factory class based on input parameters, and all objects realize a common interface; common variants include simple factories, factory methods and abstract factories, which are suitable for different complexities.

There are two types of conversion: implicit and explicit. 1. Implicit conversion occurs automatically, such as converting int to double; 2. Explicit conversion requires manual operation, such as using (int)myDouble. A case where type conversion is required includes processing user input, mathematical operations, or passing different types of values ??between functions. Issues that need to be noted are: turning floating-point numbers into integers will truncate the fractional part, turning large types into small types may lead to data loss, and some languages ??do not allow direct conversion of specific types. A proper understanding of language conversion rules helps avoid errors.
