我不知道那些“块”代表什么,但我会首先想象比字符串列表更好的抽象。
这是您可以解决的一种方法:
package cruft;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import java.io.*;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
/**
* FileChunkParser description here
* @author Michael
* @link
* @since 12/4/12 6:06 PM
*/
public class FileChunkParser {
public static void main(String[] args) {
try {
File f = new File((args.length > 0) ? args[0] : "resources/chunk.txt");
Reader reader = new FileReader(f);
FileChunkParser parser = new FileChunkParser();
Map<Integer, List<String>> chunks = parser.parse(reader);
for (int index : chunks.keySet()) {
System.out.println(String.format("index: %d chunk: %s", index, chunks.get(index)));
}
} catch (IOException e) {
e.printStackTrace();
}
}
public Map<Integer, List<String>> parse(Reader reader) throws IOException {
Map<Integer, List<String>> chunks = new TreeMap<Integer, List<String>>();
BufferedReader br = null;
try {
if (reader != null) {
br = new BufferedReader(reader);
int chunkCount = 0;
String line = "";
List<String> chunk = null;
while ((line = br.readLine()) != null) {
if (StringUtils.isBlank(line)) {
if (chunk != null) {
chunks.put(chunkCount++, new LinkedList<String>(chunk));
chunk = null;
}
continue;
} else {
if (chunk == null) {
chunk = new LinkedList<String>();
}
chunk.add(line);
}
}
if (chunk != null) {
chunks.put(chunkCount++, chunk);
}
}
} finally {
IOUtils.closeQuietly(reader);
}
return chunks;
}
}
我用这个输入文件运行它:
this
is
how
you
do
it
see
how
it
handles
arbitrary
sized
chunks
with
any
blank
lines
between
try
it
and
see
这是输出:
index: 0 chunk: [this, is, how, you, do, it]
index: 1 chunk: [see, how, it, handles, arbitrary, sized, chunks, with, any, blank, lines, between]
index: 2 chunk: [try, it, and, see]