gpt4 book ai didi

java - 使用 StringBuilder 和 BufferedReader,如何在文本文件中的每个单词后添加逗号并生成字符串?

转载 作者:搜寻专家 更新时间:2023-11-01 03:03:46 24 4
gpt4 key购买 nike

我在一个文本文件中有一个基因名称列表,它们都在一列中。我想生成一个由逗号分隔的所有基因名称的字符串。我使用了另一个线程来帮助我走到这一步,但我一直在每个名字之间得到两个逗号。看起来它在每个名称前后都添加了一个逗号。任何指导将不胜感激!代码片段如下!

      File file = new File ("/Users/Maddy/Desktop/genelist.txt");
StringBuilder line = new StringBuilder();
BufferedReader reader = null;

try {
reader = new BufferedReader (new FileReader(file));
String text = null;

while ((text = reader.readLine()) !=null) {
line.append(text);
line.append(System.getProperty ("line.separator"));


//line.append(text);
//line.append(", ");
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
try {
if (reader !=null){
reader.close();
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
System.out.println(line.toString());
String _input= new String(line.toString());

}

最佳答案

这是使用 Apache commons 的另一种方法

List<String> slist = new ArrayList<String> ();
StringBuilder rString = new StringBuilder();
while ((text = reader.readLine()) !=null) {
sList.add(text);
}
String fullString = StringUtils.join(slist, ',');

关于java - 使用 StringBuilder 和 BufferedReader,如何在文本文件中的每个单词后添加逗号并生成字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29763760/

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