ybc

           

          讀取properties文件的簡單示例

          package ybc;

          import java.io.File;
          import java.io.FileInputStream;
          import java.io.FileOutputStream;
          import java.io.IOException;
          import java.util.Properties;


          public class GetFile {

          private Properties userList;


          public GetFile(String name,String password ) {//構造函數
          super();
          Logger log = Logger.getLogger(GetFile.class);
          log.debug("構造函數");
          userList=new Properties();
          userList.setProperty(name,password);

          }

          public Properties getUserList() throws IOException

          {

          // 判斷 userList 是否為空,如果為空,則重新加載屬性文件

          if (userList == null)

          {

          // 首先檢查保存用戶名、密碼的屬性文件是否存在

          File f = new File("d:/userFile.txt");

          // 如果文件不存在,則創建文件

          System.out.print("文件的路徑:"+f.getAbsolutePath()+"\n");

          if (!f.exists())

          f.createNewFile();

          // 創建新的 Properties 實例,該實例保存了用戶名、密碼對

          userList = new Properties();

          // 從屬性文件中加載所有的用戶名、密碼

          userList.load(new FileInputStream(f));

          }

          // 返回保存用戶名、密碼對的 Properties 實例

          return userList;
          }

          public boolean saveUserList()throws IOException

          {

          // 如果用戶列表為空,則無法保存用戶

          if (userList == null)

          {

          return false;

          }

          // 調用 Properties 類的 store 方法將用戶列表保存到文件輸出流

          userList.store(new FileOutputStream("d:/userFile.txt"), "userList");

          return true;

          }

          public static void main(String args[]){
          System.out.println("執行的第一步:保存鍵值對到文本文件中");
          GetFile g= new GetFile("ybc","ybc");

          try{if(g.saveUserList())
          System.out.print("save successfull!\n");
          }catch(IOException e){
          System.out.print(e.toString());
          }
          System.out.println("執行的第二步:取文本文件中的key對應的值");
          //用下面這個類get Userlist
          try{
          g.userList=null;//這句不加的話,它就沒真正從文本文件中取,不信你試試注釋這句,然后運行就看不到打印的文件路徑了!!!
          System.out.println("從文件中get的user鍵:ybc的值:"+g.getUserList().get("ybc")+" ");
          }catch(IOException e){
          System.out.print(e.toString());
          }
          }
          // 通過上面的演示你可以簡單了解:File、FileOutputStream、FileInputStream和Properties類的使用
          // 以上只是簡單的演示了下properties文件的讀取過程,要深入了這個類可以參考java 的 Api文檔
          }

          posted on 2008-03-28 09:19 ybc 閱讀(275) 評論(0)  編輯  收藏


          只有注冊用戶登錄后才能發表評論。


          網站導航:
           

          導航

          統計

          常用鏈接

          留言簿(1)

          隨筆檔案

          文章分類

          文章檔案

          搜索

          最新評論

          閱讀排行榜

          評論排行榜

          主站蜘蛛池模板: 星座| 茌平县| 桃园市| 蒲城县| 静海县| 永康市| 新疆| 长乐市| 德格县| 抚松县| 锡林郭勒盟| 邹城市| 佛山市| 扎鲁特旗| 临清市| 邳州市| 徐州市| 天镇县| 大城县| 福海县| 剑河县| 南江县| 武汉市| 塔河县| 张掖市| 桑植县| 乐都县| 伊宁市| 南丰县| 沁水县| 远安县| 台中县| 多伦县| 安乡县| 洱源县| 额敏县| 张北县| 内丘县| 郓城县| 丽水市| 高密市|