我对java编程非常陌生。我需要以较小的 block 读取一个巨大的java文件。例如 如果我有如下文件
a
b
c
d
e
f
g
h
我的批处理大小为 2。根据上述文件,我需要创建 4 个批处理,然后进行处理。我在此任务中不需要多线程模式。 以下是我尝试过的。我知道这很简单,而且我已经离我想要实现的目标更近了。 对代码的任何建议都会有帮助
public class testing {
public static void main(String[] args) throws IOException {
System.out.println("This is for testing");
FileReader fr = null;
try {
fr = new FileReader("C:\\Users\\me\\Desktop\\Files.txt");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
int batchSize=2;
int batchCount=0;
int lineIncr=0;
BufferedReader bfr = new BufferedReader(fr);
String line;
int nextBatch=0;
int i=0;
while((line=bfr.readLine())!= null) {
if (lineIncr <=nextBatch ) {
System.out.println(line);
int b=0;
i=i+1;
if (i==2) {
b=b+1;
System.out.println("batchSize : "+b);
System.out.println("batchSize : "+b);
}
}
}
bfr.close();
}
}
最佳答案
试试这个:
final int batchSize = 2;
Path file = Paths.get("C:\\Users\\me\\Desktop\\Files.txt");
try (BufferedReader bfr = Files.newBufferedReader(file)) {
List<String> batch = new ArrayList<>(batchSize);
for (String line; (line = bfr.readLine()) != null; ) {
batch.add(line);
if (batch.size() == batchSize) {
process(batch);
batch = new ArrayList<>(batchSize); // or: batch.clear()
}
}
if (! batch.isEmpty()) {
process(batch);
}
}
显着特点:
使用新的 NIO 2
Path
API,而不是旧的File
API。用途 try-with-resources确保
Reader
始终正确关闭。收集
List<String>
中的一批行.调用
process(List<String> batch)
方法进行处理。调用
process()
如果最后一批不完整,则使用部分批处理。
关于java - 如何使用java代码批量读取文件内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46242669/