当从文件读取时,拆分方法以在彼此之下输出值

问题描述 投票:1回答:4

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

iatadult,DDD,

iatfirst,AAA,BBB,CCC

我已经在stackoverflow上进行了勤奋的搜索,但我的解决方案似乎都没有用。我知道我必须在循环进行时进行更改。然而,我见过的所有例子都没有奏效。任何进一步的理解或技术来实现我的目标都会有所帮助。无论我缺少什么,可能都很小。请帮忙。

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);
java arrays string split line
4个回答
2
投票

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

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


2
投票

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

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

在你的情况下,obj*String类型和toString()覆盖它返回字符串本身。这就是为什么你看到用逗号分隔所有字符串的原因。

要做一些不同的事情,即:在一个单独的行中打印每个对象,你应该自己实现它,你可以在每个字符串后面添加新行字符('\n')。

java 8中可能的解决方案:

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

1
投票

与平台无关的添加新行的方法:

fileContents.add(line + System.lineSeparator);


1
投票

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

        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());
                }
© www.soinside.com 2019 - 2024. All rights reserved.