缓冲读取器读取文本直到字符

Wag*_*ith 4 java file readline while-loop bufferedreader

我使用缓冲读取器读取充满信息行的文件.一些较长的文本行扩展为多行,因此缓冲区将其视为新行.每行以';'符号结尾.所以我想知道是否有办法使缓冲读取器读取一行直到它到达';'然后返回整行作为字符串.这是我到目前为止如何使用缓冲读卡器.

  String currentLine;
        while((currentLine = reader.readLine()) != null) {
            // trim newline when comparing with lineToRemove
            String[] line = currentLine.split(" ");
            String fir = line[1];
            String las = line[2];
            for(int c = 0; c < players.size(); c++){
                if(players.get(c).getFirst().equals(fir) && players.get(c).getLast().equals(las) ){
                    System.out.println(fir + " " + las);
                    String text2 = currentLine.replaceAll("[.*?]", ".150");
                    writer.write(text2 + System.getProperty("line.separator"));
                }
            }
        }
Run Code Online (Sandbox Code Playgroud)

Mur*_*nik 10

使用a可以更容易Scanner,只需设置分隔符:

Scanner scan = new Scanner(new File("/path/to/file.txt"));
scan.useDelimiter(Pattern.compile(";"));
while (scan.hasNext()) {
    String logicalLine = scan.next();
    // rest of your logic
}
Run Code Online (Sandbox Code Playgroud)

  • `logicalLine`上还有其他新行 - 可能需要一些清理 (2认同)
  • @AmiNadimi你可以使用正则表达式:`scan.useDelimiter(Pattern.compile("[ \n]"));` (2认同)