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

Using StringBuilder and BufferedReader, how can I add commas after each word in a text file and produce a string?

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

      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, ',');

摆脱这一切:

 line.append(text);
 line.append(System.getProperty ("line.separator"));


 //line.append(text);
 //line.append(", ");

并将其替换为:

 line.append(text + ",");

此外,最好将您的 text 变量更改为:

String text = "";

我不喜欢创建 String 对象 null。这不是一个好习惯。

您可以使用 Java 8 java.util.StringJoiner:

    StringJoiner j = new StringJoiner(",");
    for (String line; (line = reader.readLine()) != null;) {
        j.add(line);
    }
    String fullString = j.toString();

有几个简单的方法...

如果您将整个文件作为一个大字符串获取(比如使用 apache commons-io),您可以这样做:

String csv = rawString.replaceAll("(?ms)$.*?^", ", ");

或者如果您将文件作为 List<String>:

List<String> lines;
String csv = lines.stream().collect(Collectors.joining(", "));

也许这会对你有所帮助。

StringBuilder builder = new StringBuilder();
    int count = 0;
    List<String> list = Files.readAllLines(Paths.get("C:","Users/Maddy/Desktop/genelist.txt"));
    for (String line : list) {
        ++count;
        builder.append(line.trim());
        if (count != list.size()) {
            builder.append(",");
        }
    }
    System.out.println(builder.toString());