0

I need help in constructing a String array in Java which would store values from a text file (.txt). The file has 82094 lines where each line contains 1 word. So, in total there are 82094 words that I want to add to my array.

Here is the file path : "F:/Word Game/Words List [UK ENGLISH].txt"

I have declared this array :

String words[]=new String[82094];

I'm not sure what to do next.

1 Answers1

1

First of all, you need to read your file line by line, then put each line in an array. I strongly recommend you to use one of java.util.List<E>'s instances. I prefer java.util.ArrayList<E>

In short, ArrayList is more flexible than a plain native array because it's dynamic. It can grow itself when needed, which is not possible with the native array. ArrayList also allows you to remove elements that are not possible with native arrays. You can read more about it here.

List<String> words = new ArrayList<String>();

try (BufferedReader br = new BufferedReader(new FileReader("YOUR_FILE_PATH"))) {
    String line;
    while ((line = br.readLine()) != null) {
       words.add(line);
    }
}

Also since java 8, you can use java.util.Stream<T> to read a file:

List<String> words = new ArrayList<String>();

try (Stream<String> lines = Files.lines(Paths.get("YOUR_FILE_PATH"), Charset.defaultCharset())) {
  lines.forEachOrdered(line -> words.add(line));
}