就像标题所说的那样,我试图编写一个程序,该程序可以从文本文件中读取单个单词并将其存储到String变量中。我知道如何使用FileReaderFileInputStream读取单个char,但是对于我尝试执行的操作无法正常工作。一旦输入了单词,我便尝试使用.equals将它们与程序中的其他String变量进行比较,因此最好将其导入为Strings。我也可以将文本文件中的整行作为字符串输入,在这种情况下,我只需要在文件的每一行中输入一个单词即可。如何从文本文件输入单词并将其存储到String变量?

编辑:
好吧,重复的帮助。它可能对我有用,但是我的问题有点不同的原因是因为重复项仅告诉您如何读取一行。我试图读取行中的单个单词。因此,基本上是将字符串拆分为String。

最佳答案

要从文本文件中读取行,可以使用以下命令(使用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
    }
}

同一事物的更紧凑,更易读的版本:
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
    }
}

要将一行大块成单个单词,可以使用String.split:
while ((line = br.readLine()) != null) {
    String[] words = line.split(" ");
    // Now you have a String array containing each word in the current line
}

09-10 05:56
查看更多