我有一个逗号分隔的配置文件.空行被忽略,无效行需要出错:
FOO,酒吧
foo2,bar3
我想将这个文件读入一个HashMap
键(foo)与值(bar)映射的位置.
做这个的最好方式是什么?
如果您可以使用x = y而不是x,y那么您可以使用Properties类.
如果你确实需要x,y然后查看java.util.Scanner,你可以设置分隔符用作分隔符(javadoc显示了这样做的例子).
import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; class Main { public static void main(final String[] argv) { final File file; file = new File(argv[0]); try { final Scanner scanner; scanner = new Scanner(file); while(scanner.hasNextLine()) { if(scanner.hasNext(".*,")) { String key; final String value; key = scanner.next(".*,").trim(); if(!(scanner.hasNext())) { // pick a better exception to throw throw new Error("Missing value for key: " + key); } key = key.substring(0, key.length() - 1); value = scanner.next(); System.out.println("key = " + key + " value = " + value); } } } catch(final FileNotFoundException ex) { ex.printStackTrace(); } } }
和属性版本(解析方式更简单,因为没有)
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.Reader; import java.util.Properties; class Main { public static void main(final String[] argv) { Reader reader; reader = null; try { final Properties properties; reader = new BufferedReader( new FileReader(argv[0])); properties = new Properties(); properties.load(reader); System.out.println(properties); } catch(final IOException ex) { ex.printStackTrace(); } finally { if(reader != null) { try { reader.close(); } catch(final IOException ex) { ex.printStackTrace(); } } } } }
最好的办法是使用java.util.Scanner类读取配置文件中的值,使用逗号作为分隔符.链接到Javadoc:
http://java.sun.com/j2se/1.5.0/docs/api/java/util/Scanner.html
示例是:
Scanner sc = new Scanner(new File("thing.config")); sc.useDelimiter(","); while (sc.hasNext()) { String token = sc.next(); }