CFG文件格式:
大多数情况下,很多程序都要保存用户的设置,办法有很多:注册表,日志文件...... 而很多程序都使用了一个专用的文件。为了方便起见,常常命名为xxx.cfg,有时甚至直接命名为Config.cfg。
这只是一个为开发及使用方便而"发明"的一个后缀名。所以,这种文件没有固定的格式,其实也并不能算作是一种文件类型。用途也仅仅是保存用户的设置,平常没有必要打开。
可以使用java里的preperties类来读取这种键值对,如cfg文件,properties文件等
示例:
大多数情况下,很多程序都要保存用户的设置,办法有很多:注册表,日志文件...... 而很多程序都使用了一个专用的文件。为了方便起见,常常命名为xxx.cfg,有时甚至直接命名为Config.cfg。
这只是一个为开发及使用方便而"发明"的一个后缀名。所以,这种文件没有固定的格式,其实也并不能算作是一种文件类型。用途也仅仅是保存用户的设置,平常没有必要打开。
可以使用java里的preperties类来读取这种键值对,如cfg文件,properties文件等
示例:
- public class TestMain {
- //根据key读取value
- public static String readValue(String filePath,String key) {
- Properties props = new Properties();
- try {
- InputStream in = new BufferedInputStream (new FileInputStream(filePath));
- props.load(in);
- String value = props.getProperty (key);
- System.out.println(key+value);
- return value;
- } catch (Exception e) {
- e.printStackTrace();
- return null;
- }
- }
- //读取properties的全部信息
- public static void readProperties(String filePath) {
- Properties props = new Properties();
- try {
- InputStream in = new BufferedInputStream (new FileInputStream(filePath));
- props.load(in);
- Enumeration en = props.propertyNames();
- while (en.hasMoreElements()) {
- String key = (String) en.nextElement();
- String Property = props.getProperty (key);
- System.out.println(key+Property);
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- //写入properties信息
- public static void writeProperties(String filePath,String parameterName,String parameterValue) {
- Properties prop = new Properties();
- try {
- InputStream fis = new FileInputStream(filePath);
- //从输入流中读取属性列表(键和元素对)
- prop.load(fis);
- OutputStream fos = new FileOutputStream(filePath);
- prop.setProperty(parameterName, parameterValue);
- //以适合使用 load 方法加载到 Properties 表中的格式,
- //将此 Properties 表中的属性列表(键和元素对)写入输出流
- prop.store(fos, "Update '" + parameterName + "' value");
- } catch (IOException e) {
- System.err.println("Visit "+filePath+" for updating "+parameterName+" value error");
- }
- }
- public static void main(String[] args) {
- readValue("info.properties","url");
- writeProperties("info.properties","age","21");
- readProperties("info.properties" );
- System.out.println("OK");
- }
- }