?? 操作屬性文件.txt
字號:
/*
操作屬性文件,可以為我們的程序帶來更方便的移植性,下面是一個示例,可以讀、寫、更改屬性
讀采用了兩種方式,一種是采用Properties類,另外一種是采用資源綁定類ResourceBundle類,
下面是源程序,里面有詳細的注釋:
*/
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.Properties;
import java.util.ResourceBundle;
/**
*對屬性文件(xx.properties)的操作
*注:屬性文件一定要放在當前工程的根目錄下,也就是放在與src目錄在同一個目錄下(我的JDevelop
*是這樣的)
*/
public class OperatePropertiesFile {
public OperatePropertiesFile() {
}
/**
*采用Properties類取得屬性文件對應值
*@parampropertiesFileNameproperties文件名,如a.properties
*@parampropertyName屬性名
*@return根據屬性名得到的屬性值,如沒有返回""
*/
public static String getValueByPropertyName(String propertiesFileName,String propertyName) {
String s="";
Properties p=new Properties();//加載屬性文件讀取類
FileInputStream in;
try {
//propertiesFileName如test.properties
in = new FileInputStream(propertiesFileName);//以流的形式讀入屬性文件
p.load(in);//屬性文件將該流加入的可被讀取的屬性中
in.close();//讀完了關閉
s=p.getProperty(propertyName);//取得對應的屬性值
} catch (Exception e) {
e.printStackTrace();
}
return s;
}
/**
*采用ResourceBundel類取得屬性文件對應值,這個只能夠讀取,不可以更改及寫新的屬性
*@parampropertiesFileNameWithoutPostfixproperties文件名,不帶后綴
*@parampropertyName屬性名
*@return根據屬性名得到的屬性值,如沒有返回""
*/
public static String getValueByPropertyName_(String propertiesFileNameWithoutPostfix,String propertyName) {
String s="";
//如屬性文件是test.properties,那此時propertiesFileNameWithoutPostfix的值就是test
ResourceBundle bundel = ResourceBundle.getBundle(propertiesFileNameWithoutPostfix);
s=bundel.getString(propertyName);
return s;
}
/**
*更改屬性文件的值,如果對應的屬性不存在,則自動增加該屬性
*@parampropertiesFileNameproperties文件名,如a.properties
*@parampropertyName屬性名
*@parampropertyValue將屬性名更改成該屬性值
*@return是否操作成功
*/
public static boolean changeValueByPropertyName(String propertiesFileName,String propertyName,String propertyValue) {
boolean writeOK=true;
Properties p=new Properties();
InputStream in;
try {
in = new FileInputStream(propertiesFileName);
p.load(in);//
in.close();
p.setProperty(propertyName,propertyValue);//設置屬性值,如不屬性不存在新建
//p.setProperty("testProperty","testPropertyValue");
FileOutputStream out=new FileOutputStream(propertiesFileName);//輸出流
p.store(out,"");//設置屬性頭,如不想設置,請把后面一個用""替換掉
out.flush();//清空緩存,寫入磁盤
out.close();//關閉輸出流
} catch (Exception e) {
e.printStackTrace();
}
return writeOK;
}
}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -