1

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!

Community
  • 1
  • 1
Curly5115
  • 103
  • 1
  • 3
  • 13
  • Why an array? Why not a `Set` or `List`? PS [`BufferedReader.readLine`](http://docs.oracle.com/javase/7/docs/api/java/io/BufferedReader.html#readLine()) – obataku Aug 23 '12 at 05:45
  • I'd love to jump over and give you the answer, but that won't help you (no seriously, it won't ;)), but I can suggest you take a quick read through the Basic I/O trail http://docs.oracle.com/javase/tutorial/essential/io/ If you have any particular questions about that, let us know – MadProgrammer Aug 23 '12 at 05:46

3 Answers3

2

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.

aioobe
  • 413,195
  • 112
  • 811
  • 826
0

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.

Zéychin
  • 4,135
  • 2
  • 28
  • 27
0

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.

npinti
  • 51,780
  • 5
  • 72
  • 96