简体   繁体   中英

reading from a particular part of a line to the end (JAVA)

I have a text file. each line is a slightly different length. i want to read for the 44th character of each line to the end of the line. working fine for some line but getting a out of bounds error for others.

int lineNumber = 0;

        ArrayList<String> SenState = new ArrayList<String>();
        while((line=bufferedReader.readLine())!=null){
            lineNumber++;
            if (lineNumber >= 24) {
            String temp = line.substring(44, 46);//error occurs here for int 46
                SenState.add(temp);
                    }
                }

below is part of the text file i am reading from. i just need to get the Val of each line

Start time              End time                ID  Val
--------------------    --------------------    --  ---
25-Feb-2008 00:20:14    25-Feb-2008 00:22:57    24  1
25-Feb-2008 09:33:41    25-Feb-2008 09:33:42    24  1
25-Feb-2008 09:33:47    25-Feb-2008 17:21:12    24  1
25-Feb-2008 09:36:43    25-Feb-2008 09:37:04    5   1
25-Feb-2008 09:37:20    25-Feb-2008 09:37:23    6   1

i want to read for the 44th character of each line to the end of the line

Then just call String.substring(int) :

String temp = line.substring(44);

I strongly suspect the issue with your current code is that it's expecting to get 2 characters, when a value of 1 only has a single character. Index 46 is out of range.

(Additionally, I'd strongly advise you to follow Java naming conventions - SenState should be senState - or better, something which clearly indicates the meaning.)

Try this:

if (line.lenght() > 44) {
    String temp = line.substring(44);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM