Search code examples
javafilewhile-loopbufferedreaderreadline

Buffered Reader read text until character


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

Solution

  • 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
    }