如何快速向文件中写入 1 亿个 ip?

2022-04-09 15:49:53 +08:00
 lsk569937453

背景:需要向一个文件中写入 1 亿个 ip ,最快的方法是什么?机器配置是 mac book,双核 cpu,8GB 内存。 我用 java 实现了一个多线程的写入,发现速度慢的要死(写入时间 5 分钟以上)。有没有人推荐一下速度写入大文件的方法,或者其他语言快速写入大文件的方案。

8036 次点击
所在节点    程序员
66 条回复
raaaaaar
2022-04-10 19:56:55 +08:00
很好,面试官由悄悄 get 一个八股
xuanbg
2022-04-11 07:02:44 +08:00
@GeruzoniAnsasu 没错,打好基础后,对新技术稍作了解即可。要用什么新技术了时临时抱佛脚学一下会用就行,用不到的东西没必要花时间去学。所以别人问我要学什么,我都告诉他没有用不要学。。。

深耕某个领域,自然会步步深入专研,这都不仅仅是学习的范畴了。
illuz
2022-04-11 07:48:27 +08:00
没人考虑 ipv6 么
AdminNB
2022-04-11 10:36:30 +08:00
瞎写了写,不知道对不对



public class Main {
@SneakyThrows
public static void main(String[] args) {
byte[][] ip = new byte[1000000][4];
long start = System.currentTimeMillis();
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream("D:\\Cache\\ip.bin"));
int count = 0;
for (int i = 0; i < 255; i++) {
for (int j = 0; j < 255; j++) {
for (int k = 0; k < 255; k++) {
for (int l = 0; l < 255; l++) {
ip[count][0] = (byte) i;
ip[count][1] = (byte) j;
ip[count][2] = (byte) k;
ip[count][3] = (byte) l;
count++;
if (count % 1000000 == 0) {
for (int m = 0; m < 1000000; m++) {
bufferedOutputStream.write(ip[m]);
}
count = 0;
}
}
}
}
}
bufferedOutputStream.close();
long end = System.currentTimeMillis();
System.out.println(end - start);
}
}

时间:144663

占用空间:15.7 GB (16,912,003,072 字节)
sbilly
2022-04-13 20:04:14 +08:00
4 * 10^9 byte 没多大吧,1G 也就 26s 的时间。随机性有保障,解析成 IP 读取的时候转换就可以了。。。

```
dd if=/dev/urandom of=/opt/disk2/tmp/ipset.data bs=4096k count=256
256+0 records in
256+0 records out
1073741824 bytes (1.1 GB, 1.0 GiB) copied, 26.4446 s, 40.6 MB/s
```
amigoOS
2022-08-14 18:54:35 +08:00

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://yangjunhui.monster/t/845892

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX