Can I read a local text file line by line into a string array?

懵懂的女人 提交于 2019-12-03 08:59:50

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!