2013-06-20 52 views
0

我從java中的屬性文件中讀取值如(\+?\s*[0-9]+\s*)+時出現問題,因爲值爲getProperty()方法的值爲(+?s*[0-9]+s*)+從java中的屬性文件中讀取正則表達式

轉義屬性文件中的值不是一個選項。

任何想法?

+0

不是一個選項_yet_?你什麼意思? – fge

+0

...不是'選項'還是'! – devnull

+0

如果沒有其他作品比它將是一個選項。 – Daniel

回答

0

使用經典BufferedReader而不只是閱讀:如果有必要

final URL url = MyClass.class.getResource("/path/to/propertyfile"); 
// check if URL is null; 

String line; 

try (
    final InputStream in = url.openStream(); 
    final InputStreamReader r 
     = new InputStreamReader(in, StandardCharsets.UTF_8); 
    final BufferedReader reader = new BufferedReader(r); 
) { 
    while ((line = reader.readLine()) != null) 
     // process line 
} 

適應Java 6中......

+0

它的工作原理,但這裏的意義在哪裏?如果您決定爲此使用屬性文件,那麼爲什麼將它們寫入的方式會導致它們失效?如果你決定做一些自定義的事情,不要叫他們屬性文件,但別的東西。只是逃避反斜槓... –

+0

@JoeriHendrickx meh,不要問_me_:p – fge

1

我覺得這個類可能是反斜槓問題解決在屬性文件。

import java.io.BufferedReader; 
import java.io.FileReader; 
import java.io.IOException; 
import java.util.HashMap; 

public class ProperProps { 

    HashMap<String, String> Values = new HashMap<String, String>(); 

    public ProperProps() { 
    }; 

    public ProperProps(String filePath) throws java.io.IOException { 
     load(filePath); 
    } 

    public void load(String filePath) throws IOException { 
     BufferedReader reader = new BufferedReader(new FileReader(filePath)); 
     String line; 
     while ((line = reader.readLine()) != null) { 
      if (line.trim().length() == 0 || line.startsWith("#")) 
       continue; 

      String key = line.replaceFirst("([^=]+)=(.*)", "$1"); 
      String val = line.replaceFirst("([^=]+)=(.*)", "$2"); 
      Values.put(key, val); 

     } 
     reader.close(); 
    } 


    public String getProperty(String key) { 
     return Values.get(key); 
    } 


    public void printAll() { 
     for (String key : Values.keySet()) 
      System.out.println(key +"=" + Values.get(key)); 
    } 


    public static void main(String [] aa) throws IOException { 
     // example & test 
     String ptp_fil_nam = "my.prop"; 
     ProperProps pp = new ProperProps(ptp_fil_nam); 
     pp.printAll(); 
    } 
} 
1

我非常晚來回答這個問題,但也許這可以幫助別人,在這裏結束。

Java的較新版本(不知道哪個,我使用8)支持通過\\來表示我們習慣於正常\轉義值。

例如,在你的情況下,(\\+?\\s*[0-9]+\\s*)+是你在找什麼。

相關問題