有时候我们需要将某些参数的值写在程序外的文件中,让程序从这些文件中读取参数值。这样,我们改变这些参数值时,不必修改源程序。 例如 xx.properties
name=example;
然后程序中读取这个参数值: String propName="name";
String value=""; Properties prop=newProperties(); try{ String path=System.getProperty("user.dir"); --获得工程的路径名 prop.load(newFileInputStream(path +File.separator "storage.properties")); --这里从工程的路径中装载propeties文件 或者 properties.load(new ClassPathResource("xx.properties").getInputStream());--从classpath加载文件 value=prop.getProperty(propName); --获取参数值 System.out.println("value=" value); }catch(FileNotFoundExceptionfnfe){ System.out.println("file\"storage.properties\"notfound"); fnfe.printStackTrace(); }catch(IOExceptionioe){ ioe.printStackTrace(); } returnvalue; 好了,如果我们想改变name的值 public static void setProperty(String key, String value) { properties.setProperty(key, value); try { properties.store(new FileOutputStream(new ClassPathResource( "xx.properties").getFile()), null); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } |
|