Buffered Reader read text until character

17.5k views Asked by At

I am using a buffered reader to read in a file filled with lines of information. Some of the longer lines of text extend to be more than one line so the buffered views them as a new line. Each line ends with ';' symbol. So I was wondering if there was a way to make the buffered reader read a line until it reaches the ';' then return the whole line as a string. Here a how I am using the buffered reader so far.

  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"));
                }
            }
        }
2

There are 2 answers

5
Mureinik On BEST ANSWER

It would be much easier to do with a Scanner, where you can just set the delimiter:

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
}
1
John On

To answer your question directly, it is not possible. Buffered Reader cannot scan stream in advance to find this character and then return everything before target character.

When you read from stream with Buffered Reader you are consuming characters and you cannot really know character without reading.

You could use inherited method read() to read only single character and then stop when you detect desired character. Granted, this is not good thing to do because it contradicts the purpose of BufferedReader.