gpt4 book ai didi

java - 在java中处理大文件

转载 作者:行者123 更新时间:2023-11-29 04:43:59 25 4
gpt4 key购买 nike

如何解析像 1.2GB 这样的大文件,其中文件的总行数是 36259190。如何将每一行解析为一个对象并将其保存在列表中。

我每次都会收到 OutOfMemmoryError

List<Point> points = new ArrayList<>();

public void m2() throws IOException {
try (BufferedReader reader = Files.newBufferedReader(Paths.get(DATAFILE))) {
reader.lines().map(s -> s.split(","))
.skip(0)
.forEach(p -> points.add(newPoint(p[0], p[1], p[2])));
}
}


class Point {
String X;
String Y;
String Z;
}

最佳答案

注意您的数据类型。我很确定你的观点不是由三个文本片段组成的。所以根据实际类型定义Point的字段,例如使用 intdouble。这些原始数据类型比它们的 String 表示消耗更少的内存。

class Point {
double x, y, z;
Point(double x, double y, double z) {
this.x = x;
this.y = y;
this.z = z;
}
Point(String x, String y, String z) {
this.x = Double.parseDouble(x);
this.y = Double.parseDouble(y);
this.z = Double.parseDouble(z);
}
}

然后收集你的数据文件作为

public List<Point> m2() throws IOException {
try(BufferedReader reader = Files.newBufferedReader(Paths.get(DATAFILE))) {
return reader.lines().map(s -> s.split(","))
.map(a -> new Point(a[0], a[1], a[2]))
.collect(Collectors.toList());
}
}

然后,正如其他人所指出的,注意为您的 JVM 分配的内存。使用上面的点类,您可以毫无问题地使用 ~1½ GiB 的堆处理 36 个 Mio 实例......

关于java - 在java中处理大文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38030105/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com