Hi, im trying to read a text file into my program. It simply contains a
dictionary of commonly used words, but i want to store this list of
words as an array so that I will be able to make use of it later when
comparing against other text files. So how do I do this?(read in the
file as an array i mean) Any suggestions+code would be much
appreciated,thanks
Roedy Green - 07 Feb 2006 13:43 GMT
>Hi, im trying to read a text file into my program. It simply contains a
>dictionary of commonly used words, but i want to store this list of
>words as an array so that I will be able to make use of it later when
>comparing against other text files. So how do I do this?(read in the
>file as an array i mean) Any suggestions+code would be much
>appreciated,thanks
Let's say it is a HashMap. Just store the HashMap as a single
serialiased object.
see http://mindprod.com/jgloss/serialization.html
http://mindprod.com/applets/fileio.html
to generate some sample code.

Signature
Canadian Mind Products, Roedy Green.
http://mindprod.com Java custom programming, consulting and coaching.
Ranganath Kini - 07 Feb 2006 13:55 GMT
Try this program, it uses Generics feature compatible in JDK 5.0 or
above:
/*
* WordReader.java - A program to read words from a file
*/
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.List;
import java.util.ArrayList;
public class WordReader {
public static void main( String[] args ) {
// will store the words read from the file
List<String> wordList = new ArrayList<String>();
BufferedReader br = null;
try {
// attempt to open the words file
br = new BufferedReader( new FileReader( "words.txt" ) );
String word;
// loop and read a line from the file as long as we dont
get null
while( ( word = br.readLine() ) != null )
// add the read word to the wordList
wordList.add( word );
} catch( IOException e ) {
e.printStackTrace();
} finally {
try {
// attempt the close the file
br.close();
} catch( IOException ex ) {
ex.printStackTrace();
}
}
// initialize a new string array equal to the size of the
wordList
String[] words = new String[ wordList.size() ];
// call the wordList's toArray method to and transfer items
from
// wordList to our string array words
wordList.toArray( words );
// loop and display each word from the words array
for( int i = 0; i < words.length; i++ )
System.out.println( words[ i ] );
}
}
Hope it helps!