gpt4 book ai didi

Java Buffered FileWriter 仅写入 50% 的输入行

转载 作者:行者123 更新时间:2023-11-29 05:06:11 31 4
gpt4 key购买 nike

我的 TAB 分隔输入文件有 100 万行,它看起来像这样:

id  name    artist_name genre   notoriete_fr    notoriete_us    notoriete_uk    notoriete_it    notoriete_sp    notoriete_no    notoriete_de    notoriete_wd
1 10ème bougie 113 rap 0 -5 -5 -5 -5 -5 -5 -5
2 I'm not in love 10cc pop 1 1 1 1 1 1 1 1
5 Generation Black Rebel Motorcycle Club rock 0 0 0 0 0 0 0 0

我编写了文件格式转换代码,输出文件如下所示:

id:ID;genre;notoriete_fr:int;notoriete_us:int;notoriete_uk:int;notoriete_sp:int;notoriete_de:int;notoriete_it:int;notoriete_no:int;notoriete_wd:int;:LABEL
t1;rap;0;-5;-5;-5;-5;-5;-5;-5;Track
t5;rock;0;0;0;0;0;0;0;0;Track

我有两个问题:

  • 输出文件只有输入文件行的 50%
  • 输出文件有缺失的行,例如t2 的行丢失了

这是我的代码,提前致谢!

注意:我还在 new BufferedWriter()/Reader() 中添加了缓冲区大小,没有影响。

    public static void main(String[] args) throws Exception {

BufferedReader br = null;
BufferedWriter bw = null;

try{

// prepare input file
File inFile = new File(inputFile);
br = new BufferedReader(new FileReader(inFile));
String line = "";
String cvsSplitBy = "\t";

// prepare output file
File outFile = new File(outputFile);
bw = new BufferedWriter(new FileWriter(outFile));

// Write header
bw.write("id:ID;genre;notoriete_fr:int;notoriete_us:int;notoriete_uk:int;notoriete_sp:int;notoriete_de:int;notoriete_it:int;notoriete_no:int;notoriete_wd:int;:LABEL\n");

while ((line = br.readLine()) != null) {
// READING
line = br.readLine();
String[] features = line.split(cvsSplitBy);
// WRITING
bw.write("t"+features[0]+";"+features[3]+";"+features[4]+";"+features[5]+";"+features[6]+";"+features[7]+";"+features[8]+";"+features[9]+";"+features[10]+";"+features[11]+";Track\n");
}

} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}

最佳答案

the output file only has 8.3% of input file lines

就您的代码而言,应该缺失 50% 的行。您在大小上存在差异,因为父文件中的数据与您正在创建的文件中的数据格式不同。我这样说是因为您的代码跳过了备用行。

让我解释一下,在你的 while 循环条件下,你正在使用 line = br.readLine() 读取第 1 行。现在在 while 循环的第一行你再次使用 line = br.readLine() 这将读取文件的第 2 行。您正在使用它来写入数据,因此第 2 行数据被写入。现在在第二个循环中,在 while 循环条件下,您正在读取文件的第 3 行,而在 while 循环的第一行中,您正在读取文件的第 4 行,并且这一行被写入。所以你看到你得到了 50% 的输出。

现在您认为您理解了为什么输出文件中的行变少了。所以简单的解决方案是去掉 while 循环的第一行,让条件保持不变。

关于Java Buffered FileWriter 仅写入 50% 的输入行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30304330/

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