Java Properties save and load to file

Description

Java Properties save and load to file

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Properties;

public class Main {
  public static void main(String args[]) throws Exception {
    Properties p = new Properties();
    p.load(new FileInputStream("test.txt"));

    p.store(new FileOutputStream("t.txt"),"no comments");
  }/*from w ww.  j a  va 2 s . c o m*/
}

A simple database that uses a property list.

/*  *//*from ww w  . java 2 s . c  om*/
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;

public class Main {
  public static void main(String args[]) throws IOException {
    Properties ht = new Properties();
    FileInputStream fin = null;
    // Try to open phonebook.dat file.
    try {
      fin = new FileInputStream("phonebook.dat");
    } catch (FileNotFoundException e) {
      // ignore missing file
    }

    /*
     * If phonebook file already exists, load existing telephone numbers.
     */
    try {
      if (fin != null) {
        ht.load(fin);
        fin.close();
      }
    } catch (IOException e) {
      System.out.println("Error reading file.");
    }

    ht.put("a", "aa");
    ht.put("b", "bb");
    ht.put("c", "cc");

    FileOutputStream fout = new FileOutputStream("phonebook.dat");
    ht.store(fout, "Telephone Book");
    fout.close();

    String value = (String) ht.get("aa");
    System.out.println(value);

  }
}



PreviousNext

Related