How to read in a text file in as an array?

H

heano30

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
 
R

Roedy Green

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.
 
R

Ranganath Kini

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!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,764
Messages
2,569,565
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top