-1

I would like to read in a file (game-words.txt) via a buffered reader into an ArrayList of Strings. I already set up the buffered reader to read in from game-words.txt, now I just need to figure out how to store that in an ArrayList. Thanks ahead for any help and patience! Here is what I have so far:

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOExecption;

class Dictionary{
     String [] words; // or you can use an ArrayList
     int numwords;

    // constructor: read words from a file
    public Dictionary(String filename){ }
    BufferedReader br  = null;
    String line;

    try {

        br = new BufferedReader(new FileReader("game-words.txt"));

    while ((line = br.readLine()) != null){
            System.out.println(line);
    }
    } catch (IOExecption e) {

        e.printStackTrace();
    }

}
java_guy
  • 75
  • 1
  • 7

3 Answers3

2

Reading strings into array:

Automatic:

List<String> strings = Files.readAllLines(Path);

Manual:

List<String> strings = new ArrayList<>();
while ((line = br.readLine()) != null){
            strings.add(line);
    }

Splitting lines to words (if one line contains several words):

for(String s : strings) {
    String[] words = s.split(" "); //if words in line are separated by space
}
1

Yes, you can use an arrayList to store the words you are looking to add. You can simply use the following to deserialize the file.

ArrayList<String> pList = new ArrayList<String>();

public void deserializeFile(){
    try{
        BufferedReader br = new BufferedReader(new FileReader("file_name.txt"));
        String line = null; 
        while ((line = br.readLine()) != null) {
            // assuming your file has words separated by space
            String ar[] = line.split(" ");
            Collections.addAll(pList, ar);
        }
    }
    catch (Exception ex){
        ex.printStackTrace();
    }
}
The Roy
  • 2,178
  • 1
  • 17
  • 33
1

This could be helpful too:

class Dictionary{
 ArrayList<String> words = new ArrayList<String>(); // or you can use an ArrayList
 int numwords;String filename;

// constructor: read words from a file
public Dictionary(String filename){ 
     this.filename =filename;
 }
BufferedReader br  = null;
String line;

try {

    br = new BufferedReader(new FileReader("game-words.txt"));

while ((line = br.readLine()) != null){
        words.add(line.trim());
}
} catch (IOExecption e) {

    e.printStackTrace();
}

}

I have used trim which will remove the leading and the trailing spaces from the words if there are any.Also, if you want to pass the filename as a parameter use the filename variable inside Filereader as a parameter.

Denis
  • 1,219
  • 1
  • 10
  • 15