Rotary Heart
Rotary Heart

Reputation: 1969

Get int from text file and set it to variable

I'm trying to get the int value of a text file that have text like:

123456789 12345678 1234567 123456 12345 1234 123 12 1

as you can see every number is different and they are in a same line separated by a "space". I need to get the values separated. to get something like this:

INT1 = 123456789, INT2 = 12345678, INT3 = 1234567;

and so on. I don't create the text so I don't know how much numbers and groups they are, but they are always separated by a "space". I know how to read it. This is how I'm reading it:

try {
    TEST1 = new BufferedReader(new FileReader("/sdcard/test.txt")).readLine();

    } catch (NumberFormatException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    TEST.setText(""+scaling_available_frequencies);

and I got this output

194208 776175 958253 767883 700246 243663 966618 345199 945363 459833

NOTE: This is just a test.txt that I created to see if it works. The current code will ask the user for entering path and file name.

Now how can I set them to a variable per group?

Thanks

Upvotes: 1

Views: 1335

Answers (2)

Wenhui
Wenhui

Reputation: 658

This is one way to parse the String to an integer array:

public int[] toIntArray( String stringFromFile ){

    String[] allStrings = stringFromFile.split( "\\s" );
    int[] intArray = new int[allStrings.length];
    for( int i = 0; i < allStrings.length; ++i ){
        try{
            intArray[i] = Integer.parseInt( allStrings[i] );
        }catch( NumberFormatException e ){
            // Do whatever you think is appropriated
            intArray[i] = -1;
        }
    }
    return intArray;
}

Hope this helps.

Upvotes: 2

fangmobile
fangmobile

Reputation: 859

I believe readLine() get you String. You will need to use the Split() method of String and pass in the regularExpression (whitespace).

then you will need to use Integer.parseInt( ) method and pass in every string to parse them into Integer. you also need a loop to do the parse until nothing left

Upvotes: 1

Related Questions