gpt4 book ai didi

java - 在数据集中查找一行并复制到java中的另一个文件

转载 作者:行者123 更新时间:2023-12-01 06:13:34 25 4
gpt4 key购买 nike

我正在寻找一个小代码片段,它将查找第一列中有多少个特定数字单元格,并将 1/4 行(所有行)剪切到另一个文件。例如,我有以下文件:

数据集.txt:

0 139 0.22 0.34 0.48 0.50 0.42 0.29 0.39

0 140 0.44 0.35 0.48 0.50 0.44 0.52 0.59

0 141 0.27 0.42 0.48 0.50 0.37 0.38 0.43

0 142 0.16 0.43 0.48 0.50 0.54 0.27 0.37

1 143 0.06 0.61 0.48 0.50 0.49 0.92 0.37

代码将查找第一列中有多少个 0 并将 1/4 行放入另一个文件,我得到如下文件:

myFile.txt:

0 139 0.22 0.34 0.48 0.50 0.42 0.29 0.39

我的代码:

public static void main(String[] args) {
String in = "File.txt";
String out = "File_new.txt";
convert(in, out);
}

private static void convert(String inPath, String outPath) {
try {
BufferedReader reader = new BufferedReader(new FileReader(inPath));
BufferedWriter writer = new BufferedWriter(new FileWriter(outPath));
String line;
while((line = reader.readLine()) != null) {

String[] aaa = line.split(" ");
String newLine = "";
if(aaa[0].equals("0"))
for(int i =0; i < aaa.length; i++)
newLine += aaa[i]+' ';
newLine += '\n';
writer.write(newLine);
// ?

}
reader.close();
writer.close();
} catch(Exception exc) {
System.out.print(exc.getMessage());
}
}

while 内部的实现应该是什么样的?我做了这个:这个函数将行写入从 0 开始的新文件行,现在如何在复制到新文件后删除这一行?

最佳答案

首先,如果我正确理解你的问题,你只需要在第一个字符是 0 时执行代码。我会做类似的事情:

while(has next character) {
while (first character is != 0) {
writer.print(...);
...;
}
}

这只是您想要完成的任务的伪代码。请尝试自己编写此内容,如果不能,请进行编辑。希望这对您有帮助!

编辑**

下面列出了执行此操作的代码:

while(reader.hasNext()) {
while (reader.nextDouble() == 0.0) {
writer.print(reader.nextLine());
}
}

关于java - 在数据集中查找一行并复制到java中的另一个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29752644/

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