【发布时间】:2012-09-17 21:06:13
【问题描述】:
我有一个分号分隔的输入文件,其中第一列是 3 个字符的固定宽度代码,而其余列是一些字符串数据。
001;first_data_str;second_data_str;third_data_str;fourth_data_str
001;first_data_str;second_data_str;third_data_str;fourth_data_str
002;first_data_str;second_data_str;third_data_str;fourth_data_str
003;first_data_str;second_data_str;third_data_str;fourth_data_str
001;first_data_str;second_data_str;third_data_str;fourth_data_str
003;first_data_str;second_data_str;third_data_str;fourth_data_str
001;first_data_str;second_data_str;third_data_str;fourth_data_str
002;first_data_str;second_data_str;third_data_str;fourth_data_str
002;first_data_str;second_data_str;third_data_str;fourth_data_str
003;first_data_str;second_data_str;third_data_str;fourth_data_str
003;first_data_str;second_data_str;third_data_str;fourth_data_str
003;first_data_str;second_data_str;third_data_str;fourth_data_str
002;first_data_str;second_data_str;third_data_str;fourth_data_str
001;first_data_str;second_data_str;third_data_str;fourth_data_str
我想根据第一列的不同值将上述文件划分为多个文件。
例如在上面的例子中,第一列有三个不同的值,所以我将文件分成三个文件,即。 001.txt、002.txt、003.txt
输出文件应包含作为第一行的项目计数和作为剩余行的数据。
所以有 5 001 行,所以 001.txt 将是:
5
first_data_str;second_data_str;third_data_str;fourth_data_str
first_data_str;second_data_str;third_data_str;fourth_data_str
first_data_str;second_data_str;third_data_str;fourth_data_str
first_data_str;second_data_str;third_data_str;fourth_data_str
first_data_str;second_data_str;third_data_str;fourth_data_str
同样,002 文件的第一行为 4,然后是 4 行数据,003 文件的第一行为 5,然后是 5 行数据。
考虑到具有超过 100,000 行的非常大的输入文件,实现此目标的最有效方法是什么?
我写了下面的代码来读取文件中的行:
try{
FileInputStream fstream = new FileInputStream(this.inputFilePath);
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
while ((strLine = br.readLine()) != null) {
String[] tokens = strLine.split(";");
}
in.close();
}catch(IOException e){
e.printStackTrace();
}
【问题讨论】:
-
您是否考虑过让一个阅读器和三个编写器,在一行中读取并将其写入适当的编写器?亲en.wikipedia.org/wiki/KISS_principle
-
@AnthonyGrist,10 万或 10 万是 10 万。
-
@JohnB:您假设只有 3 个作者。但是只有在我阅读了整个文件后才能回答“有多少作者”的问题,这会给我一组标记[0],即我必须制作的输出文件的数量。
-
似乎是一个足够小的文件来读取整个数据并根据标签将其拆分为多个列表。这是正确的,还是您一次只需要在内存中保留少量文件?
-
001.txt 文件可以包含“000005”而不是“5”作为其第一(计数)行吗?数据线的典型长度是多少,以了解所需内存的总量?