2014-11-09 21 views
1

我在java中有一個正則表達式的任務,我有一個問題。從屬性中讀取的正則表達式

sentences = text.split(); 

如何傳遞到()從regexp.properties正則表達式文件

regexp.DECLARATIVE_SENTENCE = "\\."; 

例如。

我可以用一個恆定像

public static final String DECLARATIVE_SENTENCE = "\\."; 

,比讓

sentences = text.split(DECLARATIVE_SENTENCE); 

,但我需要閱讀的說法,從屬性文件。我怎樣才能做到這一點?以資源包爲例?

回答

-2
import java.util.ResourceBundle; 

ResourceBundle rb = ResourceBundle.getBundle(resourceBundleName); 
rb.getString(DECLARATIVE_SENTENCE) 
0

如果我的理解正確,您希望從屬性文件加載正則表達式值。

要做到這一點,您可以使用Java中名爲Properties的類。

public Properties GetPropertiesFile(String location) throws IOException { 
    Properties prop = new Properties(); 
    FileInputStream inputStream = null; 

    try 
    { 
     inputStream = new FileInputStream(location); 
     prop.load(inputStream); 
    } finally { 
     if (inputStream != null) { 
     inputStream.close(); 
     } 
    } 

    return prop; 
} 

您可能必須與FileInputStream發揮和利用getClass().getClassLoader().getResourceAsStream這取決於你的情況下,但是這應該讓你接近。

這裏是你如何使用上面的功能:

Properties prop = GetPropertiesFile("regexp.properties"); 
String regex = prop.getProperty("DECLARATIVE_SENTENCE"); 

String[] ret = str.split(regex); 

您可能需要更改屬性取決於您的配置文件的位置,甚至在FileInputStream如果屬性文件是一個資源)。