Search code examples
javastringfilewriterprintwriter

Reading a string below a string from a file


For example, I were to save contact details on a .txt file and after that is saved, I would want to view the contact details of the person only by entering the name.

For example, if I were to have a .txt file containing these strings,

Name: Shiroe
Contact Number: 1234567890
Name: Kirito
Contact Number: 0987654321

and I entered "Shiroe" as the contact name to be viewed. My expected output would be,

Name: Shiroe
Contact Number: 1234567890

So, bottom line, is it possible to read a string below a string (read "Shiroe"/"Name: Shiro" first and then reads the line below/after "Shiroe") to use as an output? Or am I asking the wrong question?


Solution

  • You could do something like this... It's hard to mock a correct snippet without any code of yours shown, but the logic should apply...

    try(BufferedReader br = new BufferedReader(new FileReader("yourFile.txt"))) {
            StringBuilder builder = new StringBuilder();
            String line = br.readLine();
            Boolean needNextLine = false;
    
            while (line != null) {
                if (needNextLine) {
                    sb.append(line)
                    needNextLine = false;
                    sb.append(System.lineSeparator());
                }
    
                if (line.contains("Shiroe")) {     // hardcoded
                     sb.append(line);
                     needNextLine = true;
                     sb.append(System.lineSeparator());
                }
    
                line = br.readLine();
            }
            String toBeReturned = sb.toString();
        }