javaproperties

0.8.2 · active · verified Thu Apr 09

javaproperties is a Python library that provides comprehensive support for reading and writing Java `.properties` files, encompassing both the simple line-oriented format and XML. It offers a straightforward API inspired by Python's `json` module, alongside a `Properties` class designed to emulate the behavior of Java 8's `java.util.Properties` as closely as possible in Python. The library is actively maintained, with the latest version 0.8.2 released in December 2024, and its release cadence is irregular, with significant gaps between major versions.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to use `javaproperties` to serialize Python dictionaries to Java `.properties` strings and files, and deserialize them back. It also shows the usage of the `Properties` class, which offers an API similar to Java's `java.util.Properties`.

import javaproperties
import io

# Example data to work with
data = {
    "key": "value",
    "host:port": "127.0.0.1:80",
    "snowman": "☃",
    "goat": "🐐",
    "multiline_value": "line1\\nline2"
}

# 1. Serialize a Python dictionary to a .properties string
print("--- DUMPING TO STRING ---")
properties_string = javaproperties.dumps(data, sort_keys=True, timestamp=None)
print(properties_string)

# 2. Deserialize a .properties string back to a Python dictionary
print("\n--- LOADING FROM STRING ---")
loaded_data_string = javaproperties.loads(properties_string)
print(loaded_data_string)

# 3. Serialize to a file-like object (using StringIO for demonstration)
print("\n--- DUMPING TO/LOADING FROM FILE ---")
with io.StringIO() as fp:
    javaproperties.dump(data, fp, sort_keys=True, timestamp=None, encoding='latin-1')
    fp.seek(0) # Rewind to beginning to read
    file_content = fp.read()
    print("File content:\n", file_content)

    fp.seek(0) # Rewind again for loading
    loaded_data_file = javaproperties.load(fp, encoding='latin-1')
    print("Loaded from file:", loaded_data_file)

# 4. Using the Properties class (Java-like interface)
print("\n--- USING PROPERTIES CLASS ---")
props = javaproperties.Properties()
props.update(data)
print(f"Properties object (dict-like): {props}")
print(f"Value for 'snowman': {props.get('snowman')}")

# Storing to a file with Properties class
with io.StringIO() as fp_props:
    props.store(fp_props, timestamp=None, encoding='latin-1')
    fp_props.seek(0)
    print("Properties class output:\n", fp_props.read())

view raw JSON →