Search code examples
javabytebufferedreader

How to extract values between specific sequence in java


This is the FILE I am reading How to get a specific value from this file.

I want to get data

Starting form 2000 to 466 character , starting from 4000 to 550(It can be there or ellse it will be empty) and data from 6000 to 328 characters.

ie

Line 1 : Starts from character 2000 to 466 characters
Line 2 : starts from character 4000 to 550 characters
Line 3 : starts from character 4000 to 550 characters
Line 4 : starts from character 6000 to 328 characters

And ignore the remaining part mainly the file header and file footer.

What I did so far is

UPDATE

StringBuilder sb = new StringBuilder();
newSize = in.readLine(buffer);
System.out.println("newsize-------------"+newSize);
while (newSize > 0) {
 String str = buffer.toString();
 sb.append(str);
 sb.append("\n");
 newSize = in.readLine(buffer);
}
String s = sb.toString();
/*
 * differentiating header,body and footer
 */
if(s.length() >0){

 String header = sb.toString().substring(0,466);
 System.out.println("header-------------------"+header);

 //unable to get body part
}

How to get the body part?


Solution

  • You can do it by:

    • Read the whole content of the file in a String variable.
    • call substring method for your specific char index

    Note: you have to check the string variable length before calling substring method to avoid the out of bound exception.

    UPDATE

    If i were you, ill not use a fixed value to get sub string value, but ill use indexOf method to determine the index that i should sub my string.

    For Example:

    int startIndex= fileContent.indexOf("some unique starting characters");
    int endIndex = fileContent.indexOf("some unique endingcharacters");