how to put all words from a file in an array java

http‮s‬://www.lautturi.com
how to put all words from a file in an array java

To put all words from a file in an array in Java, you can use the readAllLines method of the Files class to read the lines of the file into a List, and then use the split method of the String class to split each line into an array of words.

Here is an example of how you can put all words from a file in an array in Java:

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class WordArray {
    public static void main(String[] args) throws IOException {
        Path filePath = Paths.get("words.txt");
        List<String> lines = Files.readAllLines(filePath);

        List<String> words = new ArrayList<>();
        for (String line : lines) {
            String[] lineWords = line.split(" ");
            words.addAll(Arrays.asList(lineWords));
        }

        String[] wordArray = words.toArray(new String[0]);
    }
}

In this example, the main method uses the readAllLines method to read the lines of the file into a List of strings. Then, it uses a for loop to iterate over the lines and split each line into an array of words using the split method. The split method uses a regular expression to specify the delimiter between the words, which in this case is a space character.

Finally, it converts the List of words into an array using the toArray method and stores it in the wordArray variable.

This code will read the words from the file and store them in the wordArray array, which you can then use to perform different operations on the words, such as sorting or filtering them.

Created Time:2017-11-01 20:42:59  Author:lautturi