If I got a .txt file named words.txt and I want to catch the words to input them into an arraylist how do I do that. I know buffered reader exists but I dont quite get how to use it. All words are seperated by a space or an enter key. It has to then for example filter out words that are not 4 characters long and place the 4 long words in an arraylist to use later. For example I got this txt file :
one > gets ignored
two > gets ignored
three > gets ignored
four > caught and put into for example arraylist
five > 4 long so gets caught and put into arraylist
six > ignored
seven > ignored
eight > ignored
nine > caught because its 4 char long
ten > ignored
You can do it using streams and NIO.2
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Main {
public static void main(String[] args) {
Path path = Paths.get("words.txt");
try (Stream<String> lines = Files.lines(path)) {
List<String> list = lines.filter(word -> word.length() == 4)
.collect(Collectors.toList());
System.out.println(list);
}
catch (IOException xIo) {
xIo.printStackTrace();
}
}
}
Here is my words.txt file:
one
two
three
four
five
six
seven
eight
nine
ten
And running the above code, using the above file, prints the following:
[four, five, nine]
Alternatively, you can use a Scanner
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Path source = Paths.get("words.txt");
try (Scanner scanner = new Scanner(source)) {
List<String> list = new ArrayList<>();
while (scanner.hasNextLine()) {
String word = scanner.nextLine();
if (word.length() == 4) {
list.add(word);
}
}
System.out.println(list);
}
catch (IOException xIo) {
xIo.printStackTrace();
}
}
}
Note that both the above versions of class Main
use try-with-resources.
Yet another way is to use class java.io.BufferedReader (since you mentioned it in your question).
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
File f = new File("words.txt");
try (FileReader fr = new FileReader(f);
BufferedReader br = new BufferedReader(fr)) {
List<String> list = new ArrayList<>();
String line = br.readLine();
while (line != null) {
if (line.length() == 4) {
list.add(line);
}
line = br.readLine();
}
System.out.println(list);
}
catch (IOException xIo) {
xIo.printStackTrace();
}
}
}