Skip to content Skip to sidebar Skip to footer

Can I Read A Local Text File Line By Line Into A String Array?

The question 'How to read a local (res/raw) file line by line?' deals with a similar issue but I was unable to construct a solution base on the answers provided there. I did get a

Solution 1:

Okay, so nobody else has helped you out here ... here goes.

Essentially you've made a wrong turn in your understanding of how to use API classes.

Your code is attempting to define the DataInputStream class. You want to use the one that is already provided by the API instead. By redefining the class you are actually masking the API class (you definitely don't want that).

So if you look at the documentation for DataInputStream you'll see a constructor. This allows you to create an instance of a class. This is what you want instead :)

InputStream buildinginfo = getResources().openRawResource(R.raw.testbuilding);
DataInputStream myDIS = new DataInputStream(buildinginfo);

//you've now got an instance of DataInputStream called myDIS

String firstString = myDIS.readLine();

//voila ... your firstString variable should contain some text

There's also an issue with you array code ... but I would not use an array in this way.

You should use ArrayList, then read the lines in a while loop so you don't need to tinker with the size.

First let's get rid of this line (I'll comment it out:

//String firstString = myDIS.readLine();

And create an instance of an ArrayList which is a template class so note the String in the angle brackets denotes what sort of elements we want in our array:

ArrayList<String> list = new ArrayList<String>();

You can use the add method to add elements to the arraylist. We're going to do the whole thing in one go, don't worry I'll explain after ...

String myLine; //declare a variable

//now loop through and check if we have input, if so append it to list

while((myLine=myDIS.readline())!=null) list.add(myLine);

The last line is a bit chewy but when you assign the myLine variable this returns a result which you can compare with NULL ... once the last line is read, the readline function will return null. The condition of the while loop equates to false and drops out of the loop.

There is a simple helper function called toArray to turn your array list into a simple array.

String[] myStringArray = list.toArray(new String[list.size()])

You now have the desired output. I would suggest watching some videos on Android to get a general feel for the language, but I hope this helped you inderstand where the mistake was.


Post a Comment for "Can I Read A Local Text File Line By Line Into A String Array?"