Like the title says, im trying to write a program that can read individual words from a text file and store them to String
variables. I know how to use a
To read lines from a text file, you can use this (uses try-with-resources):
String line;
try (
InputStream fis = new FileInputStream("the_file_name");
InputStreamReader isr = new InputStreamReader(fis, Charset.forName("UTF-8"));
BufferedReader br = new BufferedReader(isr);
) {
while ((line = br.readLine()) != null) {
// Do your thing with line
}
}
More compact, less-readable version of the same thing:
String line;
try (BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("the_file_name"), Charset.forName("UTF-8")))) {
while ((line = br.readLine()) != null) {
// Do your thing with line
}
}
To chunk a line into individual words, you can use String.split:
while ((line = br.readLine()) != null) {
String[] words = line.split(" ");
// Now you have a String array containing each word in the current line
}