如何从文本文件Java中读取单个单词(或行)? [英] How to read a single word (or line) from a text file Java?
问题描述
就像标题所说,我试图编写一个程序,可以从文本文件中读取单个单词并将它们存储到 String
变量中。我知道如何使用 FileReader
或 FileInputStream
来读取单个 char
但是我正在尝试这个不会工作。一旦我输入单词,我试图将这些与我的程序中的其他String变量进行比较,使用.equals,这样我最好能够导入为Strings。我也可以将文本文件中的整行输入为String,在这种情况下,我只在文件的每一行放一个单词。如何从文本文件中输入单词并将其存储到String变量中?
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 FileReader
or FileInputStream
to read a single char
but for what I'm trying to this wont work. Once I input the words I am trying to compare these with other String variables in my program using .equals so it would be best if I can import as Strings. I am also okay with inputting an entire line from a text file as a String in which case Ill just put one word on each line of my file. How do I input words from a text file and store them to String variables?
编辑:
好的,那种重复的帮助。它可能适合我,但我的问题有点不同的原因是因为副本只告诉如何读取单行。我试图阅读该行中的单个单词。所以基本上拆分线String。
Okay, that duplicate sort of helps. It might work for me but the reason my question is a little different is because the duplicate only tells how to read a single line. Im trying to read the individual words in the line. So basically splitting the line String.
推荐答案
要从文本文件中读取行,您可以使用它(使用try-with-resources):
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
}
}
要将一行分成单个单词,你可以使用< a href =http://docs.oracle.com/javase/8/docs/api/java/lang/String.html#split-java.lang.String- =noreferrer> String.split :
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
}
这篇关于如何从文本文件Java中读取单个单词(或行)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!