我有一个逗号分隔的配置文件。空行被忽略,无效行需要出错:
FOO,酒吧
foo2,bar3
我想将此文件读入HashMap
,其中键(foo)映射为值(bar)。
这样做的最佳方式是什么?
答案 0 :(得分:6)
如果你可以使用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();
}
}
}
}
}
答案 1 :(得分:5)
最好的办法是使用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();
}
答案 2 :(得分:0)
try {
BufferedReader cfgFile = new BufferedReader(new FileReader(new File("config.file")));
String line = null;
// Read the file line by line
while ((line = cfgFile.readLine()) != null) {
line.trim();
// Ignore empty lines
if (!rec.equals("")) {
String [] fields = line.split(",");
String key = fields[0];
String value = fields[1];
// TODO: Check for more than 2 fields
// TODO: Add key, value pair to Hashmap
} // if
} // while
cfgFile.close();
} catch (IOException e) {
System.out.println("Unexpected File IO Error");
}
答案 3 :(得分:0)
我个人使用一个名叫Stephen Ostermiller的人的罐子,这是他的Labeled CSV解析器。这是一些示例代码。
LabeledCSVParser lcsvp = new LabeledCSVParser(
new CSVParser(
new StringReader(
"Name,Phone\n" +
"Stewart,212-555-3233\n" +
"Cindy,212-555-8492\n"
)
)
);
while(lcsvp.getLine() != null){
System.out.println(
"Name: " + lcsvp.getValueByLabel("Name")
);
System.out.println(
"Phone: " + lcsvp.getValueByLabel("Phone")
);
}