I have this java method which returns an ArrayList, but I want to return an Array of Strings. The method reads the file words.txt (contains all words with a word on each line), and I want to store those words into an Array of Strings.
Heres the code I already have:
public static ArrayList<String> readFile(){
File myFile=new File("./src/folder/words.txt");
Scanner s1=null;
//Creates ArrayList to store each String aux
ArrayList<String> myWords = new ArrayList<String>();
try {
s1 = new Scanner(myFile);
}catch (FileNotFoundException e) {
System.out.println("File not found");
e.printStackTrace();
}
while(s1.hasNext()){
String aux=s1.next();
System.out.println(aux);
}
s1.close();
return myWords;
}
Can I change this code to return a String []?
3 Answers 3
You can call List.toArray(String[]) to convert the List<String> to a String[]. I would also prefer a try-with-resources over explicitly closing the Scanner and a List<String> interface. Something like,
public static String[] readFile() { // <-- You could pass File myFile here
File myFile = new File("./src/folder/words.txt");
// Creates ArrayList to store each String aux
List<String> myWords = new ArrayList<>();
try (Scanner s1 = new Scanner(myFile)) {
while (s1.hasNext()) {
String aux = s1.next();
System.out.println(aux);
}
} catch (FileNotFoundException e) {
System.out.println("File not found");
e.printStackTrace();
}
return myWords.toArray(new String[0]);
}
2 Comments
import java.util.List; - Please click on the JavaDoc link in my answer.try using a built in function of collections class .
ArrayList<String> stringList = new ArrayList<String>();
stringList.add("x");
stringList.add("y");
stringList.add("z");
stringList.add("a");
/*ArrayList to Array Conversion */
/*You can use the toArray method of the collections class and pass the new String array object in the constructor while making a new String array*/
String stringArray[]=stringList.toArray(new String[stringList.size()]);
for(String k: stringArray)
{
System.out.println(k);
}
Comments
Add this at last:
String [] arr = myWords.toArray(new String[myWords.size()]);
return arr;
Or simply,
return myWords.toArray(new String[myWords.size()]);
ArrayListand then use this to create a new array ofStrings (as you will know how many elements you need). On a side note. You should not be referencingsrcat all, it won't exist once the program is compiled and exported. You should also not be reading froms1if there was an error, this will create aNullPointerException