Possible Duplicate:
Storing file content into an array
I'm programming a simple hangman program. I am having difficulty with opening a file, and then storing the data into an array. I can't seem to figure out how to do it. This is for a school project so if the logic seems unnecessary, just blame the man :)
I have a text file (words.txt) with ten words in it. They are in the file with a line in between each of them. They need to be imported into an array. Anyone care to help a young aspiring programmer out? Thanks for any help you can give!
I suggest you use a List<String>
(such as ArrayList<String>
) and a Scanner
(construct it using new Scanner(new File("wordfile.txt"))
, and use scanner.hasNextLine()
/scanner.nextLine()
) to read the words.
If you indeed need it to be an array, go through list.toArray
in the end.
Steps:
Open a Scanner on the file.
Count all of the lines in the file.
Initialize the array to an array with size equal to the count of the number of lines in the file.
Close the Scanner.
Open a Scanner on the file.
From 0 to yourArray.length - 1, assign the ith index of your array to the current line in the Scanner.
Close the scanner.
To read the file you can take a look at the Scanner Class
, this will allow you to iterate over the contents of your text file.
Although what you want to do is possible to achieve with an array data structure, it is not advisable, using something such as an ArrayList
will allow you to have a dynamic data structure which can then, if you want, be changed to an array using the toArray()
method.