You've got a few issues in that method to address. First of all, whenever you're dealing with file i/o, there's almost always the risk of IOException
, so you'll want to catch that somewhere. For instance, you could wrap your entire code in:
public String[] getStrings( String filename ){
try {
//Method content
} catch (IOException e) {
e.printStackTrace();
}
}
Second, arrays are fixed size, meaning you need to know up front how big the array would be. And since you don't know that (the file could have any number of lines), you need to use a variable size container, such as ArrayList
instead.
You can declare the ArrayList
as follows:
ArrayList<String> strArray = new ArrayList<String>();
That will create an empty ArrayList
. Now, instead of strArray = s1.toArray();
, use strArray.add(s1)
.
Then, to convert back to an array (for your method returns an array), use strArray.toArray(new String[]{})
. The new String[]{}
parameter is necessary to tell the compiler that this is in fact an array of strings, not one of objects in general.