Java reading a file and storing string into an arr

2019-02-20 16:31发布

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!

3条回答
唯我独甜
2楼-- · 2019-02-20 16:48

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.

查看更多
▲ chillily
3楼-- · 2019-02-20 16:54

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.

查看更多
时光不老,我们不散
4楼-- · 2019-02-20 17:04

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.

查看更多
登录 后发表回答