java讀取設定檔,java設定檔

來源:互聯網
上載者:User

java讀取設定檔,java設定檔

java 讀取檔案可以用位元組流和字元流。 由於一個漢字佔兩個位元組,所以如果設定檔中有漢字,用位元組流讀取,會出現亂碼。 用字元流則不會出現亂碼。

設定檔 b.properties 檔案如下:

family\ name = zhou
second name = dingzhao
gender = male
tel no. = +86 (-) 13913462
salary = 0.001k
職業 =java & 工程師

 

讀取設定檔的代碼如下:

Properties pro = new Properties();

try {

  FileReader in2 = new FileReader(new File("I:\\Workspaces\\MyWork\\xcserver\\src\\com\\xiaocong\\user\\service\\b.properties"));

  pro.load(in2);  

  System.out.println(pro.getProperty("family name"));

  Iterator<String> it=pro.stringPropertyNames().iterator();
    while(it.hasNext()){
    String key=it.next();
    System.out.println(key+":"+pro.getProperty(key));
  }

  in2.close();

} catch (FileNotFoundException e) {

  e.printStackTrace();

}

System.out.println(pro.getProperty("職業"));

輸出:

zhou
second:name = dingzhao
tel:no. = +86 (-) 139133462
family name:zhou
gender:male
salary:0.001k
職業:java & 工程師

java & 工程師

註:

1、設定檔中有空格的話,需要用 \ 轉義符。

2、pro.getProperty("職業")   getProperty(key)方法可以取得設定檔中變數的值。

 

位元組流代碼如下:

Properties pro = new Properties();

try {

  InputStream in2 = new BufferedInputStream (new FileInputStream("I:\\Workspaces\\MyWork\\xcserver\\src\\com\\xiaocong\\user\\service\\a.properties"));

  pro.load(in2);

  System.out.println(pro.getProperty("family name"));

  Iterator<String> it=pro.stringPropertyNames().iterator();
  while(it.hasNext()){
    String key=it.next();
    System.out.println(key+":"+pro.getProperty(key));
  }

  in2.close();

} catch (FileNotFoundException e) {

  e.printStackTrace();

}

 位元組流設定檔中的中文會變成亂碼。

  

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.