Leggere e scrivere file di properties in Rust

Mattepuffo's logo
Leggere e scrivere file di properties in Rust

Leggere e scrivere file di properties in Rust

I file di properties vengono usati principalmente nelle applicazioni Java.

Ma in realtà è possibile usarli anche in altri linguaggi come Rust.

In questo articolo vediamo come fare; cominciamo con l'aggiungere la libreria java-properties al file Cargo.toml:

[dependencies]
java-properties = "1.4.1"

Qui sotto un esempio di codice con due funzioni, una per scrivere il file e uno per leggerlo:

use java_properties::PropertiesIter;
use java_properties::write;
use std::collections::HashMap;
use std::fs::File;
use std::io::BufReader;
use std::io::BufWriter;

fn main() {
    let file_prop = "test.properties";

    write_file(file_prop);
    read_file(file_prop);
}

fn write_file(file_prop: &str) {
    let mut hash_map = HashMap::new();
    hash_map.insert("chiave".to_string(), "valore".to_string());
    hash_map.insert("chiave2".to_string(), "valore2".to_string());

    let f = File::create(&file_prop).expect("Errore");
    write(BufWriter::new(f), &hash_map).expect("Errore");
}

fn read_file(file_prop: &str) {
    let f = File::open(&file_prop).expect("Errore");
    let mut hash_map = HashMap::new();

    PropertiesIter::new(BufReader::new(f)).read_into(|k, v| {
        hash_map.insert(k, v);
    }).expect("Errore");

    for (k, v) in hash_map {
        println!("{}: {}", k, v);
    }
}

Enjoy!


Condividi

Commentami!