|
| 1 | +package cn.lynu.lyq.java_exam.utils; |
| 2 | + |
| 3 | +import java.io.File; |
| 4 | +import java.io.FileInputStream; |
| 5 | +import java.io.FileOutputStream; |
| 6 | +import java.io.IOException; |
| 7 | +import java.io.InputStream; |
| 8 | +import java.io.OutputStream; |
| 9 | +import java.net.URISyntaxException; |
| 10 | +import java.net.URL; |
| 11 | +import java.text.SimpleDateFormat; |
| 12 | +import java.util.Date; |
| 13 | +import java.util.Properties; |
| 14 | + |
| 15 | +public class PropertyUtils { |
| 16 | + |
| 17 | + private static InputStream is; |
| 18 | + private static OutputStream os; |
| 19 | + |
| 20 | + static{ |
| 21 | + try { |
| 22 | + File propFile = new File(new URL(PropertyUtils.class.getResource("/")+"mysetting.properties").toURI()); |
| 23 | + System.out.println(propFile.getAbsolutePath()); |
| 24 | + is = new FileInputStream(propFile); |
| 25 | + |
| 26 | + } catch (Exception e) { |
| 27 | + e.printStackTrace(); |
| 28 | + } |
| 29 | + } |
| 30 | + |
| 31 | + public static String getProperty(String key){ |
| 32 | + Properties prop = new Properties(); |
| 33 | + try { |
| 34 | + prop.load(is); |
| 35 | + return prop.getProperty(key); |
| 36 | + } catch (Exception e) { |
| 37 | + e.printStackTrace(); |
| 38 | + return null; |
| 39 | + } |
| 40 | + } |
| 41 | + |
| 42 | + public static void setProperty(String key, String value){ |
| 43 | + Properties prop = new Properties(); |
| 44 | + try { |
| 45 | + prop.load(is); |
| 46 | + |
| 47 | + System.out.println(prop.keySet()); |
| 48 | + prop.setProperty(key, value); |
| 49 | + File propFile = new File(new URL(PropertyUtils.class.getResource("/")+"mysetting.properties").toURI()); |
| 50 | + os = new FileOutputStream(propFile); |
| 51 | + prop.store(os, "modified at "+ new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date())); |
| 52 | + } catch (Exception e) { |
| 53 | + e.printStackTrace(); |
| 54 | + } |
| 55 | + } |
| 56 | + |
| 57 | + public static void main(String[] args) throws IOException, URISyntaxException { |
| 58 | +// InputStream is = ClassLoader.getSystemResourceAsStream("mysetting.properties"); |
| 59 | +// Properties prop = new Properties(); |
| 60 | +// prop.load(is); |
| 61 | +// prop.list(System.out); |
| 62 | +// |
| 63 | +// FileOutputStream fos = new FileOutputStream(new File(ClassLoader.getSystemResource("mysetting.properties").toURI())); |
| 64 | +// prop.setProperty("lyqtest1", "bbb"); |
| 65 | +// prop.store(fos, "store something2"); |
| 66 | +// prop.list(System.out); |
| 67 | + |
| 68 | + String test1 = getProperty("lyqtest1"); |
| 69 | + System.out.println(test1); |
| 70 | + setProperty("lyqtest0000","mmmmmmmmmmmmm"); |
| 71 | + |
| 72 | + } |
| 73 | + |
| 74 | +} |
0 commit comments