Buffered reader reads text up to character

I am using a buffered reader to read a file filled with lines of information. Some of the longer lines of text expand to more than one line, so buffering treats them as a newline. Each line ends with a character ';'

. So I was wondering if there is a way to get the buffered reader to read the line until it reaches ';'

, and then return the entire line as a string. This is how I use 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"));
                }
            }
        }

      

+3


source to share


2 answers


It would be much easier to do with 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
}

      

+8


source


To answer your question directly, this is not possible. A buffered reader cannot scan the stream ahead of time to find that character and then return everything up to the target character.

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



You can use the inherited method read()

to read only one character and then stop when you find the character you want. Of course this is not good because it goes against the purpose of the BufferedReader.

+2


source







All Articles