我有一个文本文件(制表符分隔,行换行),有 n 列。我想将该文件拆分到第四列,并为该列的每个不同值生成一个文件。
即,如果五行具有相同的列值(例如 X ),则所有这五行都将放入 x.txt 中,依此类推。
在处理结束时,如果第四列中有 m 个不同的值,我将拥有 m 个文件。您可以假设第 4 列是“日期”类型。因此本质上需要对日期列上的数据进行分区并生成不同的文件,每个文件都有指定日期的数据。
有什么简单的方法吗?
最佳答案
简单的草稿
public static void main( String[] args) throws IOException {
String[] input = {"A1\tB\tC\tD\t2012-02-10",
"A2\tB\tC\tD\t2012-02-10",
"A3\tB\tC\tD\t2012-02-08",
"A4\tB\tC\tD\t2012-02-08",
"A5\t\tC\tD\t2012-02-07",
"A6\tB\tC\tD\t2012-02-07" };
Map<String,String> map = new HashMap<String, String>();
for ( String row : input ) {
String[] cols = row.split( "\t" );
String date = cols[4];
String content = map.get( date );
content = (content == null) ? row : content + "\n" + row;
map.put( date, content );
}
for ( String filename : map.keySet() ) {
FileOutputStream fos = new FileOutputStream("c:\\" + filename );
fos.write( map.get( filename ).getBytes() );
fos.close();
}
}
注意:您应该使用正确的行分隔符和编码。
要读取输入,您可以使用 libcsv
关于java - 从一个文件生成多个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9225279/