learning
learning

Reputation: 37

how to read a text file with spaces android java

how do i read a text file with spaces into an int array when i know my file contains

"22 23 29 1 "

and such

private String readFromFile() {

    String ret = "";

    try {
        InputStream inputStream = openFileInput("mywords.txt");

        if ( inputStream != null ) {
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String receiveString = "";
            StringBuilder stringBuilder = new StringBuilder();

            while ( (receiveString = bufferedReader.readLine()) != null ) {
                stringBuilder.append(receiveString);
            }

            inputStream.close();
            ret = stringBuilder.toString();
        }
    }
    catch (FileNotFoundException e) {
        Log.e("login activity", "File not found: " + e.toString());
    } catch (IOException e) {
        Log.e("login activity", "Can not read file: " + e.toString());
    }

    return ret;
}

i used this for read till now

Upvotes: 0

Views: 1008

Answers (3)

ata
ata

Reputation: 9011

You can also use Scanner.

Scanner scanner = new Scanner(inputStream).useDelimiter(" ");

and than you can use the functions like hasNext() and next() to check and read next word. What you can do is create a ArrayList of Integers and parse as you get next().

Something like (this is just a pseudo-code)

ArrayList<Integer> list = new ArrayList<Integer>();
while(scanner.hasNext()) {
    read = scanner.next();
    list.add(Integer.parseInt(read));
}
return list;

Upvotes: 1

Darshan Lila
Darshan Lila

Reputation: 5868

For "22 23 29 1 " i.e Integers with a space try following code:

String ret="22 23 29 1 ";
ret=ret.trim();
String tok[]=ret.split(" ");
for(String s:tok) {
    System.out.println(s);
}

Output :

22
23
29
1

If you require you can parse string to integer using Integer.parseInt() .

Upvotes: 3

ppuskar
ppuskar

Reputation: 771

make a call to split(" ") on returned String you will get String array. Typecast as per your usage.

Upvotes: 0

Related Questions