隨着Guava library捏,解決辦法很簡單,優雅。我們可以通過客觀化的關鍵提高了下面的代碼,處理錯誤等等等等,但你可以做你自己
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import com.google.common.base.CharMatcher;
import com.google.common.base.Charsets;
import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import com.google.common.collect.Maps;
import com.google.common.io.Files;
import com.google.common.io.LineProcessor;
public class FileProcessor
{
private static final Splitter SPLITTER = Splitter.on(CharMatcher.WHITESPACE);
private static final Joiner KEY_BUILDER = Joiner.on("_").skipNulls();
@SuppressWarnings("unchecked")
public static void main(final String[] args) throws IOException
{
Map<String, SalaryAndDesignation> result = Files.readLines(new File("c:/1.txt"), Charsets.ISO_8859_1, new LineProcessor() {
private final Map<String, SalaryAndDesignation> result = Maps.newHashMap();
public Object getResult()
{
return result;
}
public boolean processLine(final String line) throws IOException
{
Iterator<String> columns = SPLITTER.split(line).iterator();
String id = columns.next();
String name = columns.next();
String dept = columns.next();
String key = KEY_BUILDER.join(id, name, "null".equals(dept) ? null : dept);
result.put(key, new SalaryAndDesignation(columns.next(), columns.next()));
return true;
}
});
System.out.println(result.size());
}
final static class SalaryAndDesignation
{
String salary;
String designation;
public SalaryAndDesignation(final String salary, final String designation)
{
super();
this.salary = salary;
this.designation = designation;
}
}
}
我看到使用Groovy導致較小的代碼如下(copy/pasted from here)樣本,但從未使用過它自己
new File("simple.tab").withReader{r->
line = r.readLine();
println "first line: $line"
r.splitEachLine("\t"){fields->
println "fields on line: $fields"
}
}
我很好奇,是在該文件中選擇一個分隔符還是比這更「髒」?在提出可能存在缺陷的解決方案之前,瞭解有關格式的更多信息會非常有幫助。 – xlson 2010-11-05 07:45:15
@潘 - 我回答了你的問題嗎?如果是這樣,接受答案 – 2010-12-23 16:59:34