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 閱讀(276) 評論(0)  編輯  收藏


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


          網站導航:
           

          導航

          統計

          常用鏈接

          留言簿(1)

          隨筆檔案

          文章分類

          文章檔案

          搜索

          最新評論

          閱讀排行榜

          評論排行榜

          主站蜘蛛池模板: 塘沽区| 高阳县| 高淳县| 永嘉县| 嘉禾县| 铁岭市| 平遥县| 金寨县| 阜平县| 卢氏县| 南木林县| 丰城市| 武宣县| 城口县| 琼结县| 育儿| 古交市| 永宁县| 天祝| 和政县| 琼结县| 海阳市| 珲春市| 普陀区| 军事| 江口县| 独山县| 济宁市| 荃湾区| 汝阳县| 来安县| 香港 | 黄石市| 和政县| 通城县| 元氏县| 洛宁县| 迭部县| 成安县| 普兰县| 神木县|