File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes I/O and Streams and the fly likes Read all words from a text file into an array Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » I/O and Streams
Bookmark "Read all words from a text file into an array" Watch "Read all words from a text file into an array" New topic
Author

Read all words from a text file into an array

Angela Truce
Ranch Hand

Joined: Nov 30, 2005
Posts: 47
Dear all,

Does anyone know how to rewrite the following code to read all the words from a text file since I've run it and it only reads the last line. I want to avoid using Lists since I have no knowlegde of how to use them in the code.




Thanks in advance!
Joe Ess
Bartender

Joined: Oct 29, 2001
Posts: 8907
    
    8

Welcome to the JavaRanch, Angela.
Your problem is here:

You read in a line and set array to point to the results of a split of that line, therefore array will only hold the last line in a file. A list would be the easiest way to deal with this. Otherwise you need to resize array and append the results of input.split to the previous contents. It's not difficult, just tedious.


"blabbing like a narcissistic fool with a superiority complex" ~ N.A.
[How To Ask Questions On JavaRanch]
Angela Truce
Ranch Hand

Joined: Nov 30, 2005
Posts: 47
Ok,
Say I had to rewrite the code. But only using knowledge of StringTokenizer and BufferedReaders, I have to read words from a text file consisting of several lines of several words, then put them into an array. Then, using a random number generator, select a random word from this array and store as a string.

Any takers?
Joe Ess
Bartender

Joined: Oct 29, 2001
Posts: 8907
    
    8

Angela, this sounds an awful lot like a homework problem. Why don't you tackle your assignment in manageable parts. First, solve your problem above: how to read in the file. We'd be glad to help you with any specific problems you have but in the end, one learns how to program by writing lots of code and we're not about to deprive you of that opportunity.
Angela Truce
Ranch Hand

Joined: Nov 30, 2005
Posts: 47
I have written some of the code, just wanted to compare so that I can find the problem. This part of the code is trying to read words from a text file and putting them all in the string array. But for some reason it won't work:


Joe Ess
Bartender

Joined: Oct 29, 2001
Posts: 8907
    
    8

Originally posted by Angela Truce:
But for some reason it won't work:


I'll say. That code won't even compile. Can you give us some code that will compile, then tell us what you expect it to do and what it actually does?
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Read all words from a text file into an array