split 方法在从文件读取时输出值在彼此之下

split method to output values under each other when reading from a file

我的代码工作正常,但它并排打印值,而不是逐行打印。像这样:

iatadult,DDD,

iatfirst,AAA,BBB,CCC

我在 Whosebug 上进行了认真的搜索,none 我的解决方案似乎有效。我知道我必须在循环进行时进行更改。然而,none 我见过的例子都有效。任何进一步的理解或技术来实现我的目标都会有所帮助。无论我缺少什么,都可能非常小。请帮忙

String folderPath1 = "C:\PayrollSync\client\client_orginal.txt";
File file = new File (folderPath1);
ArrayList<String> fileContents = new ArrayList<>(); // holds all matching client names in array

try {
    BufferedReader reader = new BufferedReader(new FileReader(file));// reads entire file
    String line;

    while (( line = reader.readLine()) != null) { 
        if(line.contains("fooa")||line.contains("foob")){
            fileContents.add(line);
        }
        //---------------------------------------
    }
    reader.close();// close reader
} catch (Exception e) {
    System.out.println(e.getMessage());
}

System.out.println(fileContents);

在添加到 fileContents 之前添加换行符。

fileContents.add(line+"\n");

一种独立于平台的添加新行的方法:

fileContents.add(line + System.lineSeparator);

通过直接打印列表,您正在调用方法 toString() 为打印内容的列表覆盖:

obj1.toString(),obj2.toString() .. , objN.toString()

在你的例子中,obj*String 类型,toString() 覆盖它 returns 字符串本身。这就是为什么您看到所有字符串都用逗号分隔的原因。

要做一些不同的事情,即:在单独的行中打印每个对象,您应该自己实现它,并且您可以简单地在每个字符串后附加换行符('\n')。

java8 中的可能解决方案:

String result = fileContents.stream().collect(Collectors.joining('\n'));
System.out.println(result);

以下是我的完整回答。感谢您的帮助计算器。这花了我一整天,但我有一个完整的解决方案。

        File file = new File (folderPath1);
        ArrayList<String> fileContents = new ArrayList<>(); // holds all matching client names in array 

         try {
                BufferedReader reader = new BufferedReader(new FileReader(file));// reads entire file
                String line;

                while (( line = reader.readLine()) != null) { 
                     String [] names ={"iatdaily","iatrapala","iatfirst","wpolkrate","iatjohnson","iatvaleant"};
                           if (Stream.of(names).anyMatch(line.trim()::contains)) {
                               System.out.println(line);
                               fileContents.add(line + "\n");
                           }
                }
                 System.out.println("---------------");
                reader.close();// close reader
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }