Search code examples
javastringtextjava.util.scannerbufferedreader

Problems trying to retrieve information from txt file


I'm stuck on one issue in my application. I have one text file that contains one piece of code that I need to retrieve to apply into one string variable. The problem is which is the best way to do this? I ran those samples below, but they are logically incorrect / incomplete. Take a look:

  1. Reading through line:

    BufferedReader bfr = new BufferedReader(new FileReader(Node));
    
    String line = null;
    try {
        while( (line = bfr.readLine()) != null ){
            line.contentEquals("d.href");
            System.out.println(line);
        }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    
  2. Reading through character:

    BufferedReader bfr = new BufferedReader(new FileReader(Node));
    int i = 0;
    try {
        while ((i = bfr.read()) != -1) {
             char ch = (char) i;
             System.out.println(Character.toString(ch));
        }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    };
    
  3. Reading through Scanner:

    BufferedReader bfr = new BufferedReader(new FileReader(Node));
    BufferedReader bfr = new BufferedReader(new FileReader(Node));
    int wordCount = 0, totalcount = 0;
    Scanner s = new Scanner(googleNode);
    while (s.hasNext()) {
       totalcount++;
       if (s.next().contains("(?=d.href).*?(}=?)")) wordCount++;
    }
    System.out.println(wordCount+" "+totalcount);
    

With (1.) I'm having difficult to find d.href with contains the start of the code piece.
With (2.) I can't think or find one way to store d.href as string and retrieve the rest of information.
With (3.) I can correctly find d.href but I can't retrieve pieces of the txt.

Could anyone help me please?


Solution

  • As answer of my question, I used scanner to read word by word in the text file. .contains("window.maybeRedirectForGBV") returns one boolean value, and hasNext() one string. Then, I stoped the query for my code stretch on the text file one word before I wanted and moved forward one more time to store the value of the next word on one string variable. From this point you only need to treat your string the way you want. Hope this help.

    String stringSplit = null;
               Scanner s = new Scanner(Node);
               while (s.hasNext()) {
    
                if (s.next().contains("window.maybeRedirectForGBV")){
                    stringSplit = s.next();
                    break;
                }
               }