分隔文本文件中的所有单词

Seperate all words in a text file

我想分隔文本文件中的所有单词。一行中可以有很多单词。我尝试了该代码,但没有 work.What 我可以吗?

这是文本文件:

desem ki vakitlerden
bir nisan akşamıdır
rüzgarların en ferahlatıcısı senden esiyor
sen de açıyor çiçeklerin en solmazı
ormanların en kuytusunu sen de gezmekteyim
demişken sana ormanların
senden güzeli yok
vakitlerden geçmekteyim
çiçeklerin tadı yok çiçeklerin
neyi var çiçeklerin

而且我想把所有的单词都一个一个地写下来。

String[] words = null;
String line = inputStream.nextLine();


        while (inputStream.hasNextLine()) {
            line = inputStream.nextLine();
            words = line.split(" ");
        }


            for (int i = 0; i < words.length; i++) {
                System.out.println(words[i]);
            }
        }
        inputStream.close();

使用数组列表:

 ArrayList<String> words = new ArrayList<String>();
 String line = inputStream.nextLine();


    while (inputStream.hasNextLine()) {
        line = inputStream.nextLine();
        words.addAll(Arrays.asList(line.split(" ")));
    }


        for (int i = 0; i < words.size(); i++) {
            System.out.println(words.get(i´));
        }
    }
    inputStream.close();

因为您似乎已经在使用 Scanner

而不是

while (inputStream.hasNextLine()) {
    line = inputStream.nextLine();
    words = line.split(" ");
}


    for (int i = 0; i < words.length; i++) {
        System.out.println(words[i]);
    }
}

您可以使用它的 next(),它将读取单词而不是行。这样您就可以打印所有单词而无需

  1. 阅读整行,
  2. 将此行解析为 split 成单词
  3. 存储所有单词

您的代码可能如下所示:

Scanner inputStream = new Scanner(new File("location/of/your/file.txt"));
List<String> words = new ArrayList<>();
while (inputStream.hasNext()){
    words.add(inputStream.next());
}
inputStream.close();

for (String word : words){
     //here you can do whatever you want with each word from list
     System.out.println(word);
}