import java.util.Properties; public class TestPr { public static void main(String[] arg){ Properties props = System.getProperties(); System.out.println("\n\t The program Properties:\n"); System.out.println("\n\t total properties found: "+props.size()+"\n\n"); props.list(System.out); } } |
обавяне от командния ред при пускане на програмата
java -D<key1>=<value1> -D<key2>=<value2> TestPr
---------------------------------------------
Добавяне в текста на програмата:
import
java.util.Properties;
...
Properties props = System.getProperties();
props.put(key,value); //
key, value като низове
--------------------------------------------------------
Премахване в текста на програмата:
props.remove(key);------------------------------------------
Пример -
добавяне при стартиране и промени в текста на програмата
java -DmyOutProperty=myOutPropertyValue TestPr1
import
java.util.Properties; public class TestPr1 { public static void main(String[] arg){ Properties props = System.getProperties(); props.put("myInProperty","myInPropertyValue"); System.out.println("before remove:"); System.out.println ("myInProperty has value:" +props.getProperty("myInProperty")); System.out.println ("myOutProperty has value:"+props.getProperty("myOutProperty")); props.remove("myInProperty"); props.remove("myOutProperty"); System.out.println("after remove:"); System.out.println ("myInProperty has value:"+props.getProperty("myInProperty")); System.out.println ("myOutProperty has value:"+props.getProperty("myOutProperty")); } } |
import
java.io.*; import java.util.Properties; public class FilePropS { public static void main(String[] args) { Properties prop = new Properties(); OutputStream output = null; try { output = new FileOutputStream("config.properties"); // set the properties value prop.setProperty("server", "localhost"); prop.setProperty("client", "127.0.0.1"); prop.setProperty("password", "secret"); // save properties to project root folder prop.store(output, "test property save"); } catch (IOException io) { io.printStackTrace(); } finally { if (output != null) { try { output.close(); } catch (IOException e) { e.printStackTrace(); } } } } } |
import
java.io.*; import java.util.Properties; public class FilePropR { public static void main(String[] args) { Properties prop = new Properties(); InputStream input = null; try { input = new FileInputStream("config.properties"); // load a properties file prop.load(input); // get a property value and print it out System.out.println(prop.getProperty("server")+"\n"); // listing all properties prop.list(System.out); } catch (IOException ex) { ex.printStackTrace(); } finally { if (input != null) { try { input.close(); } catch (IOException e) { e.printStackTrace(); } } } } } |