Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- String propFile = "/path/to/file";
- Properties props = new Properties();
- /*set some properties here*/
- try {
- FileOutputStream xmlStream = new FileOutputStream(propFile);
- /*this comes out unsorted*/
- props.storeToXML(xmlStream,"");
- } catch (IOException e) {
- e.printStackTrace();
- }
- String propFile = "/path/to/file";
- Properties props = new Properties();
- /*set some properties here*/
- Properties tmp = new Properties() {
- @Override
- public Set<Object> keySet()
- {
- return Collections.unmodifiableSet(new TreeSet<Object>(super.keySet()));
- }
- };
- tmp.putAll(props);
- try {
- FileOutputStream xmlStream = new FileOutputStream(propFile);
- /*this comes out SORTED! */
- tmp.storeToXML(xmlStream,"");
- } catch (IOException e) {
- e.printStackTrace();
- }
- public static void main(String[] args){
- String propFile = "/tmp/test2.xml";
- Properties props = new Properties();
- props.setProperty("key", "value");
- props.setProperty("key1", "value1");
- props.setProperty("key2", "value2");
- props.setProperty("key3", "value3");
- props.setProperty("key4", "value4");
- try {
- BufferedWriter out = new BufferedWriter(new FileWriter(propFile));
- List<String> list = new ArrayList<String>();
- for(Object o : props.keySet()){
- list.add((String)o);
- }
- Collections.sort(list);
- out.write("<?xml version="1.0" encoding="UTF-8"?>n");
- out.write("<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">n");
- out.write("<properties>n");
- out.write("<comment/>n");
- for(String s : list){
- out.write("<entry key="" + s + "">" + props.getProperty(s) + "</entry>n");
- }
- out.write("</properties>n");
- out.flush();
- out.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- Properties props = new Properties() {
- @Override
- public Set<Object> keySet(){
- return Collections.unmodifiableSet(new TreeSet<Object>(super.keySet()));
- }
- @Override
- public synchronized Enumeration<Object> keys() {
- return Collections.enumeration(new TreeSet<Object>(super.keySet()));
- }
- };
- props.put("B", "Should come second");
- props.put("A", "Should come first");
- props.storeToXML(new FileOutputStream(new File("sortedProps.xml")), null);
- props.store(new FileOutputStream(new File("sortedProps.properties")), null);
- new Properties() {
- @Override Set<Object> keySet() {
- return new TreeSet<Object>(super.keySet());
- }
- }
- Set keys = props.keySet();
- Iterator i = keys.iterator();
- Set keys = props.keySet();
- List<String> newKeys = new ArrayList<String>();
- for(Object key : keys)
- {
- newKeys.add(key.toString());
- }
- Collections.sort(newKeys);
- Iterator i = newKeys.iterator();
Add Comment
Please, Sign In to add comment