導航:首頁 > 編程語言 > java遍歷properties

java遍歷properties

發布時間:2022-07-03 20:13:45

1. 如何遍歷properties文件的鍵和值

application實際上是一個map ,你直接把所有用戶名放在一個list裡面 然後把這個list對象放進applicarion 在map.get(key)方法取這個list 用for循環遍歷列印就可以了

2. java中用Properties類載入配置文件

一個Properties只能載入一個問題,如果你需要載入多個的話只能多寫幾個了。
例如:
Properties prop = new Properties();
prop.load(ConfigUtil.class.getClassLoader().getResourceAsStream("config.properties"));

Properties prop1 = new Properties();
prop1.load(ConfigUtil.class.getClassLoader().getResourceAsStream("config.properties1"));

3. java獲取properties文件時的Can't find bundle for base name問題

如果發生ResourceBundle.getBundle("myresource") 讀取不到資源文件時,需要注意下面問題.
1,java project
僅僅需要把myresource.properties文件放在src下,如果是放在package下,則程序的filename應該package/myresource

2,j2ee的web project
1,myresource.properties要放在WEB-INF的classes下,
2,如果是使用jar來執行讀取資源文件時,該jar需要添加在lib下面,不僅僅是由IED(eclipse)配置的classpath

解釋:getBundle載入資源文件時,會讀取當前應用的classLoader,遍歷當前的classloader找出classpath,進行資源文件的綁定,如果找不到則會報出
java.util.MissingResourceException。
關鍵在於,如果使用eclipse配置應用,而且是將lib託管給elipse去載入,那麼eclipse中啟動tomcat時,應用的載入lib下的classloader和tomcat讀取應用後載入的class就不會是同一個。
tomcat啟動時,根據tomcat配置的jre,載入應用。而且應用的lib託管給eclipse,由elipse設定的jre載入lib下的jar。此時就會有2個jre環境。
解決方法是:把所有jar放到WEB-INF的lib下,由容器自己載入。當然也要在此載入到classpath下,項目編譯需要。

那個屬性文件也要加上路徑的。於是又開始新征程。這樣為了配活,再來。
static ResourceBundle rb = ResourceBundle.getBundle(ReadSource.class.getPackage().toString().substring(8)+".info");
這樣就解決了路徑問題,只要屬性文件和讀取文件在一起就可以了。

4. 在java中如何讀取properties文件

最常用讀取properties文件的方法
InputStream in = getClass().getResourceAsStream("資源Name");這種方式要求properties文件和當前類在同一文件夾下面。如果在不同的包中,必須使用:
InputStream ins = this.getClass().getResourceAsStream("/cn/zhao/properties/testPropertiesPath2.properties");
Java中獲取路徑方法
獲取路徑的一個簡單實現
反射方式獲取properties文件的三種方式

1 反射方式獲取properties文件最常用方法以及思考:
Java讀取properties文件的方法比較多,網上最多的文章是"Java讀取properties文件的六種方法",但在Java應用中,最常用還是通過java.lang.Class類的getResourceAsStream(String name) 方法來實現,但我見到眾多讀取properties文件的代碼中,都會這么干:

InputStream in = getClass().getResourceAsStream("資源Name");

這裡面有個問題,就是getClass()調用的時候默認省略了this!我們都知道,this是不能在static(靜態)方法或者static塊中使用的,原因是static類型的方法或者代碼塊是屬於類本身的,不屬於某個對象,而this本身就代表當前對象,而靜態方法或者塊調用的時候是不用初始化對象的。

問題是:假如我不想讓某個類有對象,那麼我會將此類的默認構造方法設為私有,當然也不會寫別的共有的構造方法。並且我這個類是工具類,都是靜態的方法和變數,我要在靜態塊或者靜態方法中獲取properties文件,這個方法就行不通了。

那怎麼辦呢?其實這個類就不是這么用的,他僅僅是需要獲取一個Class對象就可以了,那還不容易啊--
取所有類的父類Object,用Object.class難道不比你的用你正在寫類自身方便安全嗎 ?呵呵,下面給出一個例子,以方便交流。
import java.util.Properties;
import java.io.InputStream;
import java.io.IOException;

/**
* 讀取Properties文件的例子
* File: TestProperties.java
* User: leimin
* Date: 2008-2-15 18:38:40
*/
public final class TestProperties {
private static String param1;
private static String param2;

static {
Properties prop = new Properties();
InputStream in = Object. class .getResourceAsStream( "/test.properties" );
try {
prop.load(in);
param1 = prop.getProperty( "initYears1" ).trim();
param2 = prop.getProperty( "initYears2" ).trim();
} catch (IOException e) {
e.printStackTrace();
}
}

/**
* 私有構造方法,不需要創建對象
*/
private TestProperties() {
}

public static String getParam1() {
return param1;
}

public static String getParam2() {
return param2;
}

public static void main(String args[]){
System.out.println(getParam1());
System.out.println(getParam2());
}
}

運行結果:

151
152
當然,把Object.class換成int.class照樣行,呵呵,大家可以試試。

另外,如果是static方法或塊中讀取Properties文件,還有一種最保險的方法,就是這個類的本身名字來直接獲取Class對象,比如本例中可寫成TestProperties.class,這樣做是最保險的方法
2 獲取路徑的方式:
File fileB = new File( this .getClass().getResource( "" ).getPath());

System. out .println( "fileB path: " + fileB);

2.2獲取當前類所在的工程名:
System. out .println("user.dir path: " + System. getProperty ("user.dir"))<span style="background-color: white;">3 獲取路徑的一個簡單的Java實現</span>
/**

*獲取項目的相對路徑下文件的絕對路徑

*

* @param parentDir

*目標文件的父目錄,例如說,工程的目錄下,有lib與bin和conf目錄,那麼程序運行於lib or

* bin,那麼需要的配置文件卻是conf裡面,則需要找到該配置文件的絕對路徑

* @param fileName

*文件名

* @return一個絕對路徑

*/

public static String getPath(String parentDir, String fileName) {

String path = null;

String userdir = System.getProperty("user.dir");

String userdirName = new File(userdir).getName();

if (userdirName.equalsIgnoreCase("lib")

|| userdirName.equalsIgnoreCase("bin")) {

File newf = new File(userdir);

File newp = new File(newf.getParent());

if (fileName.trim().equals("")) {

path = newp.getPath() + File.separator + parentDir;

} else {

path = newp.getPath() + File.separator + parentDir

+ File.separator + fileName;

}

} else {

if (fileName.trim().equals("")) {

path = userdir + File.separator + parentDir;

} else {

path = userdir + File.separator + parentDir + File.separator

+ fileName;

}

}

return path;

}

4 利用反射的方式獲取路徑:
InputStream ips1 = Enumeration . class .getClassLoader() .getResourceAsStream( "cn/zhao/enumStudy/testPropertiesPath1.properties" );

InputStream ips2 = Enumeration . class .getResourceAsStream( "testPropertiesPath1.properties" );

InputStream ips3 = Enumeration . class .getResourceAsStream( "properties/testPropertiesPath2.properties" );

5. JAVA這個數組遍歷是什麼意思

private static Properties getValue(String[] variants) throws NoKeyException
{
Properties properties = new Properties();//創建一個Properties類的對象,對象名叫properties
for (String variant : variants) //使用增強型for循環(JDK1.5以後支持),:後面的是你傳入的String數組,前面是這個數組裡面的每一個元素
{
String key = variant;//把這個數組的裡面的每一個元素給key
String value = monitorClient.getValue(key);//通過key獲取對應的value值
if(value == null)//如果獲取的value是空值
throw new NoKeyException(variant);//拋出沒有該鍵的異常
properties.put(variant, value);//如果value不是空值,把鍵和獲取的值放入properties中
}
return properties;//返回properties
}

6. java中怎麼讀取properties文件

(1)load(InputStream inStream)
這個方法可以從.properties屬性文件對應的文件輸入流中,載入屬性列表到Properties類對象。如下面的代碼:
Properties pro = new Properties();
FileInputStream in = new FileInputStream("a.properties");
pro.load(in);
in.close();

(2)store(OutputStream out, String comments)
這個方法將Properties類對象的屬性列表保存到輸出流中。如下面的代碼:
FileOutputStream oFile = new FileOutputStream(file, "a.properties");
pro.store(oFile, "Comment");
oFile.close();

7. java編程中Properties類的具體作用和使用!

如果不熟悉 java.util.Properties類,那麼現在告訴您它是用來在一個文件中存儲鍵-值對的,其中鍵和值是用等號分隔的。(如清單 1 所示)。最近更新的java.util.Properties 類現在提供了一種為程序裝載和存儲設置的更容易的方法: loadFromXML(InputStreamis) 和 storeToXML(OutputStream os, String comment) 方法。

一下是詳細的說明,希望能給大家帶來幫助。

清單 1. 一組屬性示例

foo=bar
fu=baz

將清單 1 裝載到 Properties 對象中後,您就可以找到兩個鍵( foo 和 fu )和兩個值( foo 的 bar 和 fu 的baz )了。這個類支持帶 \u 的嵌入 Unicode 字元串,但是這里重要的是每一項內容都當作 String 。

清單2 顯示了如何裝載屬性文件並列出它當前的一組鍵和值。只需傳遞這個文件的 InputStream 給 load()方法,就會將每一個鍵-值對添加到 Properties 實例中。然後用 list() 列出所有屬性或者用 getProperty()獲取單獨的屬性。

清單 2. 裝載屬性

import java.util.*;
import java.io.*;

public class LoadSample {
public static void main(String args[]) throws Exception {
Properties prop = new Properties();
FileInputStream fis =
new FileInputStream("sample.properties");
prop.load(fis);
prop.list(System.out);
System.out.println("\nThe foo property: " +
prop.getProperty("foo"));
}
}

運行 LoadSample 程序生成如清單 3 所示的輸出。注意 list() 方法的輸出中鍵-值對的順序與它們在輸入文件中的順序不一樣。Properties 類在一個散列表(hashtable,事實上是一個 Hashtable 子類)中儲存一組鍵-值對,所以不能保證順序。

清單 3. LoadSample 的輸出

-- listing properties --
fu=baz
foo=bar

The foo property: bar

XML 屬性文件
這里沒有什麼新內容。 Properties 類總是這樣工作的。不過,新的地方是從一個 XML 文件中裝載一組屬性。它的 DTD 如清單 4 所示。

清單 4. 屬性 DTD

<?xml version="1.0" encoding="UTF-8"?>
<!-- DTD for properties -->
<!ELEMENT properties ( comment?, entry* ) >
<!ATTLIST properties version CDATA #FIXED "1.0">
<!ELEMENT comment (#PCDATA) >
<!ELEMENT entry (#PCDATA) >
<!ATTLIST entry key CDATA #REQUIRED>

如果不想細讀 XML DTD,那麼可以告訴您它其實就是說在外圍 <properties> 標簽中包裝的是一個<comment> 標簽,後面是任意數量的 <entry> 標簽。對每一個 <entry>標簽,有一個鍵屬性,輸入的內容就是它的值。清單 5 顯示了 清單 1中的屬性文件的 XML 版本是什麼樣子的。

清單 5. XML 版本的屬性文件

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE properties SYSTEM " http://java.sun.com/dtd/properties.dtd">
<properties>
<comment>Hi</comment>
<entry key="foo">bar</entry>
<entry key="fu">baz</entry>
</properties>

如果清單 6 所示,讀取 XML 版本的 Properties 文件與讀取老格式的文件沒什麼不同。

清單 6. 讀取 XML Properties 文件

import java.util.*;
import java.io.*;

public class LoadSampleXML {
public static void main(String args[]) throws Exception {
Properties prop = new Properties();
FileInputStream fis =
new FileInputStream("sampleprops.xml");
prop.loadFromXML(fis);
prop.list(System.out);
System.out.println("\nThe foo property: " +
prop.getProperty("foo"));
}
}

關於資源綁定的說明
雖然 java.util.Properties 類現在除了支持鍵-值對,還支持屬性文件作為 XML 文件,不幸的是,沒有內置的選項可以將ResourceBundle 作為一個 XML 文件處理。是的, PropertyResourceBundle 不使用 Properties對象來裝載綁定,不過裝載方法的使用是硬編碼到類中的,而不使用較新的 loadFromXML() 方法。

運行清單 6 中的程序產生與原來的程序相同的輸出,如 清單 2所示。

保存 XML 屬性
新的 Properties 還有一個功能是將屬性存儲到 XML 格式的文件中。雖然 store() 方法仍然會創建一個類似 清單 1所示的文件,但是現在可以用新的 storeToXML() 方法創建如 清單 5 所示的文件。只要傳遞一個 OutputStream和一個用於注釋的 String 就可以了。清單 7 展示了新的 storeToXML() 方法。

清單 7. 將 Properties 存儲為 XML 文件

import java.util.*;
import java.io.*;

public class StoreXML {
public static void main(String args[]) throws Exception {
Properties prop = new Properties();
prop.setProperty("one-two", "buckle my shoe");
prop.setProperty("three-four", "shut the door");
prop.setProperty("five-six", "pick up sticks");
prop.setProperty("seven-eight", "lay them straight");
prop.setProperty("nine-ten", "a big, fat hen");
FileOutputStream fos =
new FileOutputStream("rhyme.xml");
prop.storeToXML(fos, "Rhyme");
fos.close();
}
}

運行清單 7 中的程序產生的輸出如清單 8 所示。

清單 8. 存儲的 XML 文件

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE properties SYSTEM " http://java.sun.com/dtd/properties.dtd">
<properties>
<comment>Rhyme</comment>
<entry key="seven-eight">lay them straight</entry>
<entry key="five-six">pick up sticks</entry>
<entry key="nine-ten">a big, fat hen</entry>
<entry key="three-four">shut the door</entry>
<entry key="one-two">buckle my shoe</entry>
</properties>
在這里改了一個例子:
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
/**
* 實現properties文件的讀取
* @author haoxuewu
*/
public class Test {
public static void main(String[] args) {
try {
long start = System.currentTimeMillis();
InputStream is = new FileInputStream("conf.properties");
Properties p = new Properties();
p.load(is);
is.close();
System.out.println("SIZE : " + p.size());
System.out.println("homepage : " + p.getProperty("homepage"));
System.out.println("author : " + p.getProperty("author"));
System.out.println("school : " + p.getProperty("school"));
long end = System.currentTimeMillis();
System.out.println("Cost : " + (end - start));
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
conf.properties
# Configuration file
homepage = http://www.blogjava.net/haoxuewu
author = bbflyerwww
school = jilinjianzhugongchengxueyuan

Result
SIZE:3
homepage : http://www.blogjava.net/haoxuewu
author : bbflyerwww
school : jilinjianzhugongchengxueyuan

8. JAVA中如何讀取src下所有的properties文件

1.使用java.util.Properties類的load()方法


示例:

//文件在項目下。不是在包下!!

InputStream in = new BufferedInputStream(new FileInputStream("demo.properties")) ;

Properties p = new Properties();

p.load(in) ;

String className2 = p.getProperty("database.driver");

String url = p.getProperty("database.url");

String user = p.getProperty("database.user");

String password = p.getProperty("database.pass");

總結:如果是 在WEB上讀取properties文件,寫成下面這種。上面寫的那些只在 JavaSE 中

String path = Thread.currentThread().getContextClassLoader().getResource("").getPath();

System.out.println(path);

InputStream in = new FileInputStream(new File(path+File.separator+"mysql.properties"));

Properties prop = new Properties();

9. 如何遍歷properties文件的鍵值對並放置到application作用域里

先建個監聽器:

[java] view plain

packagecom.yjd.hy.server;

importjava.io.FileInputStream;

importjava.io.FileNotFoundException;

importjava.io.IOException;

importjava.util.HashMap;

importjava.util.Iterator;

importjava.util.Map;

importjava.util.Properties;

importjava.util.Map.Entry;

importjavax.servlet.ServletContextEvent;

importjavax.servlet.ServletContextListener;

/**

*應用上下文監聽器,讀取配置文件、字典表

*

*/

{

publicvoidcontextDestroyed(ServletContextEventarg0){

}

publicvoidcontextInitialized(ServletContextEventarg0){

/**讀取配置文件**/

StringspecialPath=System.getProperty("search.root")

+"/WEB-INF/properties/xxx.properties";

Propertiesprops=newProperties();

try{

props.load(newFileInputStream(specialPath));

}catch(FileNotFoundExceptione){

e.printStackTrace();

}catch(IOExceptione){

e.printStackTrace();

}

Map<String,String>ddMap=newHashMap<String,String>();

Iteratoritr=props.entrySet().iterator();

while(itr.hasNext()){

Entrye=(Entry)itr.next();

ddMap.put(e.getKey().toString(),e.getValue().toString());

}

arg0.getServletContext().setAttribute("xxx_dict_data",ddMap);

}

}


在Web.xml中配置監聽器:

[html] view plain

<!--載入全局配置文件、字典數據的監聽器-->

<listener>

<listener-class>com.yjd.hy.server.MyServletContextListener</listener-class>

</listener>

Java中獲取:

[java] view plain

Objectobj=ServletActionContext.getServletContext().getAttribute("xxx_dict_data");


Jsp頁面中直接獲取:

[html] view plain

<%@pagelanguage="java"import="java.util.*"pageEncoding="UTF-8"%>

<%

Stringpath=request.getContextPath();

StringbasePath=request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";

%>

<!DOCTYPEHTMLPUBLIC"-//W3C//DTDHTML4.01Transitional//EN">

<html>

<head>

<basehref="<%=basePath%>">

<title>MyJSP'MyJsp.jsp'startingpage</title>

<metahttp-equiv="pragma"content="no-cache">

<metahttp-equiv="cache-control"content="no-cache">

<metahttp-equiv="expires"content="0">

<metahttp-equiv="keywords"content="keyword1,keyword2,keyword3">

<metahttp-equiv="description"content="Thisismypage">

</head>

<body>

<prename="code"class="html"><spanstyle="white-space:pre"></span>${xxx_dict_data['aaa.bbb']}</pre></body></html>

<pre></pre>

<pre></pre>


閱讀全文

與java遍歷properties相關的資料

熱點內容
圓命令畫法 瀏覽:303
如果給電腦e盤文件加密 瀏覽:799
javaswing項目 瀏覽:773
androidsdksetup 瀏覽:1001
pdf怎麼設置中文 瀏覽:124
安卓手機用什麼軟體看倫敦金 瀏覽:962
魅族文件夾無名稱 瀏覽:787
蘇黎世無人機演算法 瀏覽:871
核桃編程和小碼王的融資 瀏覽:681
微積分教材pdf 瀏覽:723
寫python給微信好友發消息 瀏覽:336
蚊帳自營米加密 瀏覽:418
學校推薦核桃編程 瀏覽:802
湖南農信app怎麼導明細 瀏覽:471
福特abs編程 瀏覽:506
如何自學安卓手機 瀏覽:437
以太坊源碼共識機制 瀏覽:910
單片機探測器 瀏覽:870
demo編程大賽作品怎麼運行 瀏覽:51
學歷提升用什麼手機軟體App 瀏覽:938