存储单词而不是行

时间:2014-11-14 12:50:32

标签: java arrays split readfile

String line = "";
List<String> fruit = new LinkedList<String>();

try {
    br = new BufferedReader(new FileReader(filePath));
    try {
        while((line = br.readLine()) != null)
        {

            //System.out.println(line);
            String[] words = line.split(" ");

            for (String word : words) {
              if (word.equals("fruit")) {
                line = br.readLine();
                fruit.add(line);

              }

            }


        }
        br.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
} catch (FileNotFoundException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

String[] fruitArray = fruit.toArray(new String[0]);
for (String s : fruitArray) {
    System.out.println(s);
  }
}
}

我在数组中的代码存储行

但我的问题是我需要在数组中存储单词用空格分隔 我的文字是这样的:

  水果苹果木瓜樱桃猕猴桃

     

香蕉

我的结果是:

  

香蕉

谢谢你们

1 个答案:

答案 0 :(得分:1)

更改行:

String[] words = line.split(" ");

通过

String[] words = line.split("\\s+");