我有这样的代码
public static void main(String[] args) throws Exception {
long start = System.currentTimeMillis();
List<String> matches = new Vector<>(); // Race condition for ArrayList??
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream("AHugeFile.txt")));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("output.txt")));
reader.lines().parallel()
.filter(s -> s.matches("someFancyRegEx"))
.forEach(s -> {
matches.add(s);
try {
writer.write(s);
writer.newLine();
} catch (Exception e) {
System.out.println("error");
}
}
);
out.println("Processing took " + (System.currentTimeMillis() - start) / 1000 + " seconds and matches " + matches.size());
reader.close();
writer.flush();
writer.close();
}我注意到,如果在第3行用ArrayList替换Vector,那么每次匹配都会得到不同的结果。我只是想在流上弄脏我的手,但是假设forEach同时执行,试图写到ArrayList,而ArrayList漏掉了一些写!对于向量,结果是一致的。
我有两个问题:
发布于 2015-08-18 08:56:26
以下是Java 6中写方法的代码片段。
public void write(String s, int off, int len) throws IOException {
synchronized (lock) {
ensureOpen();
int b = off, t = off + len;
while (b < t) {
int d = min(nChars - nextChar, t - b);
s.getChars(b, b + d, cb, nextChar);
b += d;
nextChar += d;
if (nextChar >= nChars)
flushBuffer();
}
}
}
}发布于 2015-08-18 09:32:36
首先要做的是:定义您是否关心写行的顺序; (been there, done that)。
第二:使用Java 8提供的工具;它有两个非常方便的方法,即Files.lines()和Files.write()。
第三:正确处理你的资源!在您的代码中不能保证文件描述符将正确关闭。
第四:.matches()每次都会重新创建一个Pattern,您总是使用相同的正则表达式进行过滤.你在浪费资源。
第五:考虑到BufferedWriter的写方法是同步的,那么并行性不会带来什么好处。
我会这样做:
public static void writeFiltered(final Path srcFile, final Path dstFile,
final String regex)
throws IOException
{
final Pattern pattern = Pattern.compile(regex);
final List<String> filteredLines;
try (
// UTF-8 by default
final Stream<String> srcLines = Files.lines(srcFile);
) {
filteredLines = srcLines.map(pattern::matcher)
.filter(Matcher::matches)
.collect(Collectors.toList());
}
// UTF-8 by default
Files.write(dstFile, filteredLines);
}https://stackoverflow.com/questions/32067786
复制相似问题