Search code examples
javaioreadline

can we choose/modify where readLine() method starts reading?


I searched through all the topics and since I couldn't find a similar problem, I'd like to ask the following question:

given the sample code:

try (BufferedReader helpRdr= new BufferedReader (new FileReader (helpfile))){

        do {
                                    //read characters until # is found
        ch= helpRdr.read();
                                    //now see if topics match
        if (ch=='#') {

            topic= helpRdr.readLine();
            if (what.compareTo(topic)==0) {                     //found topic

                do {

                    info=helpRdr.readLine();
                    if (info!=null) System.out.println (info);
                } while ((info!=null) && (info.compareTo("")!=0));

and a sample file content:

"#if if (condition) statement; else statement; "

The question is:

why does readLine() method in the above example doesn't read '#', instead having the following output:if (condition) statement; else statement;

Thanks for help in advance folks!


Solution

  • This happens because you have already read the # character and therefore is no longer there when you do read() or readLine().

    What you can do is this:

    String ch = helpRdr.readLine();
    if (ch.startsWith("#")) {
     // Do your stuff
    }
    

    Or this:

    topic = ch + helpRdr.readLine();