1 3 package jodd.util; 4 5 import java.io.File ; 6 import java.io.FileInputStream ; 7 import java.io.FileOutputStream ; 8 import java.io.IOException ; 9 import java.util.Iterator ; 10 import java.util.Properties ; 11 12 15 public class PropertiesUtil { 16 17 19 26 public static Properties createFromFile(String fileName) throws IOException { 27 return createFromFile(new File (fileName)); 28 } 29 30 37 public static Properties createFromFile(File file) throws IOException { 38 Properties prop = new Properties (); 39 loadFromFile(prop, file); 40 return prop; 41 } 42 43 52 public static void loadFromFile(Properties p, String fileName) throws IOException { 53 loadFromFile(p, new File (fileName)); 54 } 55 56 65 public static void loadFromFile(Properties p, File file) throws IOException { 66 FileInputStream fis = null; 67 try { 68 fis = new FileInputStream (file); 69 p.load(fis); 70 } finally { 71 if (fis != null) { 72 fis.close(); 73 } 74 } 75 } 76 77 78 86 public static void writeToFile(Properties p, String fileName) throws IOException { 87 writeToFile(p, new File (fileName), null); 88 } 89 90 99 public static void writeToFile(Properties p, String fileName, String header) throws IOException { 100 writeToFile(p, new File (fileName), header); 101 } 102 103 111 public static void writeToFile(Properties p, File file) throws IOException { 112 writeToFile(p, file, null); 113 } 114 115 124 public static void writeToFile(Properties p, File file, String header) throws IOException { 125 FileOutputStream fos = null; 126 try { 127 fos = new FileOutputStream (file); 128 p.store(fos, header); 129 } finally { 130 if (fos != null) { 131 fos.close(); 132 } 133 } 134 } 135 136 137 139 149 public static Properties subset(Properties p, String prefix, boolean stripPrefix) { 150 if (StringUtil.isBlank(prefix) == true) { 151 return p; 152 } 153 if (prefix.endsWith(".") == false) { 154 prefix += '.'; 155 } 156 Properties result = new Properties (); 157 int baseLen = prefix.length(); 158 Iterator iti = p.keySet().iterator(); 159 while (iti.hasNext()) { 160 String key = (String ) iti.next(); 161 if (key.startsWith(prefix) == true) { 162 result.setProperty(stripPrefix == true ? key.substring(baseLen) : key, p.getProperty(key)); 163 } 164 } 165 return result; 166 } 167 168 } 169 | Popular Tags |