Ricerca…


introduzione

L'oggetto properties contiene coppie di chiavi e valori sia come stringa. La classe java.util.Properties è la sottoclasse di Hashtable.

Può essere utilizzato per ottenere il valore della proprietà in base alla chiave della proprietà. La classe Proprietà fornisce metodi per ottenere dati dal file delle proprietà e memorizzare i dati nel file delle proprietà. Inoltre, può essere utilizzato per ottenere le proprietà del sistema.

Vantaggio del file delle proprietà

La ricompilazione non è richiesta, se le informazioni vengono modificate dal file delle proprietà: Se vengono modificate le informazioni da

Sintassi

  • In un file di proprietà:
  • chiave = valore
  • #commento

Osservazioni

Un oggetto Properties è una mappa le cui chiavi e valori sono stringhe per convenzione. Sebbene i metodi di Map possano essere utilizzati per accedere ai dati, i metodi type-safe getProperty , setProperty e stringPropertyNames vengono generalmente utilizzati.

Le proprietà sono spesso archiviate in file di proprietà Java, che sono semplici file di testo. Il loro formato è documentato accuratamente nel metodo Properties.load . In sintesi:

  • Ogni coppia chiave / valore è una riga di testo con uno spazio, uguale ( = ), o due punti ( : ) tra la chiave e il valore. Gli uguali o i due punti possono avere qualsiasi quantità di spazi bianchi prima e dopo di essa, che viene ignorata.
  • Lo spazio bianco principale viene sempre ignorato, lo spazio bianco finale è sempre incluso.
  • Una barra rovesciata può essere utilizzata per sfuggire a qualsiasi carattere (eccetto in minuscolo u ).
  • Una barra rovesciata alla fine della riga indica che la riga successiva è una continuazione della linea corrente. Tuttavia, come per tutte le linee, gli spazi bianchi iniziali nella linea di continuazione vengono ignorati.
  • Proprio come nel codice sorgente di Java, \u seguita da quattro cifre esadecimali rappresenta un carattere UTF-16.

La maggior parte dei framework, incluse le strutture di Java SE come java.util.ResourceBundle, carica i file delle proprietà come InputStreams. Quando si carica un file di proprietà da un InputStream, quel file può contenere solo caratteri ISO 8859-1 (ovvero caratteri nell'intervallo 0-255). Qualsiasi altro personaggio deve essere rappresentato come \u escape. Tuttavia, puoi scrivere un file di testo in qualsiasi codifica e utilizzare lo strumento native2ascii (che viene fornito con ogni JDK) per farlo scappare per te.

Se si sta caricando un file di proprietà con il proprio codice, può essere in qualsiasi codifica, purché si crei un Reader (come un InputStreamReader ) basato sul set di caratteri corrispondente. È quindi possibile caricare il file utilizzando load (Reader) anziché il metodo di caricamento legacy (InputStream).

È anche possibile memorizzare le proprietà in un semplice file XML, che consente al file stesso di definire la codifica. Tale file può essere caricato con il metodo loadFromXML . La DTD che descrive la struttura di tali file XML si trova all'indirizzo http://java.sun.com/dtd/properties.dtd .

Caricamento delle proprietà

Per caricare un file di proprietà in bundle con la tua applicazione:

public class Defaults {

    public static Properties loadDefaults() {
        try (InputStream bundledResource =
            Defaults.class.getResourceAsStream("defaults.properties")) {

            Properties defaults = new Properties();
            defaults.load(bundledResource);
            return defaults;
        } catch (IOException e) {
            // Since the resource is bundled with the application,
            // we should never get here.
            throw new UncheckedIOException(
                "defaults.properties not properly packaged"
                + " with application", e);
        }
    }

}

Avvertenza sui file di proprietà: spazi bianchi finali

Dai un'occhiata da vicino a questi due file di proprietà che sono apparentemente completamente identici:

inserisci la descrizione dell'immagine qui

tranne che non sono davvero identici:

inserisci la descrizione dell'immagine qui

(gli screenshot provengono da Notepad ++)

Poiché lo spazio bianco finale è conservato, il valore di lastName sarebbe "Smith" nel primo caso e "Smith " nel secondo caso.

Molto raramente questo è ciò che gli utenti si aspettano e uno e può solo speculare perché questo è il comportamento predefinito della classe Properties . È tuttavia facile creare una versione avanzata di Properties che corregge questo problema. La seguente classe, TrimmedProperties , fa proprio questo. È una sostituzione drop-in per la classe di proprietà standard.

import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.util.Map.Entry;
import java.util.Properties;

/**
 * Properties class where values are trimmed for trailing whitespace if the
 * properties are loaded from a file.
 *
 * <p>
 * In the standard {@link java.util.Properties Properties} class trailing
 * whitespace is always preserved. When loading properties from a file such
 * trailing whitespace is almost always <i>unintentional</i>. This class fixes
 * this problem. The trimming of trailing whitespace only takes place if the
 * source of input is a file and only where the input is line oriented (meaning
 * that for example loading from XML file is <i>not</i> changed by this class).
 * For this reason this class is almost in all cases a safe drop-in replacement
 * for the standard <tt>Properties</tt>
 * class.
 *
 * <p>
 * Whitespace is defined here as any of space (U+0020) or tab (U+0009).
 * * 
 */
public class TrimmedProperties extends Properties {

    /**
     * Reads a property list (key and element pairs) from the input byte stream.
     * 
     * <p>Behaves exactly as {@link java.util.Properties#load(java.io.InputStream) }
     * with the exception that trailing whitespace is trimmed from property values
     * if <tt>inStream</tt> is an instance of <tt>FileInputStream</tt>.
     * 
     * @see java.util.Properties#load(java.io.InputStream) 
     * @param inStream the input stream.
     * @throws IOException if an error occurred when reading from the input stream.
     */
    @Override
    public void load(InputStream inStream) throws IOException {
        if (inStream instanceof FileInputStream) {
            // First read into temporary props using the standard way
            Properties tempProps = new Properties();
            tempProps.load(inStream);
            // Now trim and put into target
            trimAndLoad(tempProps);
        } else {
            super.load(inStream);
        }
    }

    /**
     * Reads a property list (key and element pairs) from the input character stream in a simple line-oriented format. 
     * 
     * <p>Behaves exactly as {@link java.util.Properties#load(java.io.Reader)}
     * with the exception that trailing whitespace is trimmed on property values
     * if <tt>reader</tt> is an instance of <tt>FileReader</tt>.
     * 
     * @see java.util.Properties#load(java.io.Reader) }
     * @param reader the input character stream.
     * @throws IOException if an error occurred when reading from the input stream.
     */
    @Override
    public void load(Reader reader) throws IOException {
        if (reader instanceof FileReader) {
            // First read into temporary props using the standard way
            Properties tempProps = new Properties();
            tempProps.load(reader);
            // Now trim and put into target
            trimAndLoad(tempProps);
        } else {
            super.load(reader);
        }
    }

    private void trimAndLoad(Properties p) {
        for (Entry<Object, Object> entry : p.entrySet()) {
            if (entry.getValue() instanceof String) {
                put(entry.getKey(), trimTrailing((String) entry.getValue()));
            } else {
                put(entry.getKey(), entry.getValue());
            }
        }
    }

    /**
     * Trims trailing space or tabs from a string.
     *
     * @param str
     * @return
     */
    public static String trimTrailing(String str) {
        if (str != null) {
            // read str from tail until char is no longer whitespace
            for (int i = str.length() - 1; i >= 0; i--) {
                if ((str.charAt(i) != ' ') && (str.charAt(i) != '\t')) {
                    return str.substring(0, i + 1);
                }
            }
        }
        return str;
    }
}

Salvataggio delle proprietà come XML

Memorizzazione delle proprietà in un file XML

Il modo in cui si archiviano i file delle proprietà come file XML è molto simile al modo in cui li si archivia come file .properties . Semplicemente invece di usare lo store() storeToXML() .

public void saveProperties(String location) throws IOException{
    // make new instance of properties
    Properties prop = new Properties();
    
    // set the property values
    prop.setProperty("name", "Steve");
    prop.setProperty("color", "green");
    prop.setProperty("age", "23");
    
    // check to see if the file already exists
    File file = new File(location);
    if (!file.exists()){
        file.createNewFile();
    }
    
    // save the properties
    prop.storeToXML(new FileOutputStream(file), "testing properties with xml");
}

Quando apri il file, sarà simile a questo.

screenshot del file fatto

Caricamento delle proprietà da un file XML

Ora per caricare questo file come properties è necessario chiamare il loadFromXML() posto di load() che si utilizzerà con i file regolari .propeties .

public static void loadProperties(String location) throws FileNotFoundException, IOException{
    // make new properties instance to load the file into
    Properties prop = new Properties();
    
    // check to make sure the file exists
    File file = new File(location);
    if (file.exists()){
        // load the file
        prop.loadFromXML(new FileInputStream(file));
        
        // print out all the properties
        for (String name : prop.stringPropertyNames()){
            System.out.println(name + "=" + prop.getProperty(name));
        }
    } else {
        System.err.println("Error: No file found at: " + location);
    }
}

Quando si esegue questo codice, nella console verrà visualizzato quanto segue:

age=23
color=green
name=Steve


Modified text is an extract of the original Stack Overflow Documentation
Autorizzato sotto CC BY-SA 3.0
Non affiliato con Stack Overflow