-1

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?

Rod Galangco
  • 37
  • 1
  • 9
  • 5
    Yes it is possible! Try it and then make a question when you have actually a problem :) – Jorge Campos Mar 09 '15 at 16:02
  • Read up to Shiro, then read the next line until it starts with the attribute name then parse it to get the data, basically. Is this file huge, if not consider reading in a List of contacts... – Tony Hopkinson Mar 09 '15 at 16:05
  • why don't you save them in a JsonArray of JsonObjects? – nafas Mar 09 '15 at 16:19

2 Answers2

1

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();
    }
Dragan
  • 455
  • 4
  • 12
  • Apologies for the late reply. This is exactly what I am looking for. (though I was thinking of sandwich-ing the strings and then pulling out the one in the middle, but this one is better). – Rod Galangco Mar 11 '15 at 14:10
0

It is quite possible


  • search the entire String(sat "text", holding data from the text file) for the occurrence of "Name:Shiroe" using int startPos = text.indexOf("Name:Shiroe")
  • That would return you the index of the first occurrence of character('N') in that "Name:Shiroe".
  • Now search for another occurrence of "Name" after "Name:Shiroe" by using endPos = text.indexOf("Name",pos+1)
  • Now extract the substring form startPos till endPos using text.subString(startPos,endPos);

int startPos = text.indexOf("Name:Shiroe");
int endPos = text.indexOf("Name",startPos);
String details = text.subString(startPos,endPos);

cheers :)

prasad vsv
  • 1,138
  • 8
  • 10