如何打印每行的第一个单词?

时间:2018-12-02 04:04:15

标签: java string arraylist bufferedreader

我有一个文本文件,内容如下:

1. Bananas that are not green
2. Pudding that is not vanilla
3. Soda that is not Pepsi
4. Bread that is not stale

我只希望它打印出每行的第一个单词 不包含数字!

它应打印为:

Bananas
Pudding    
Soda    
Bread

这是我的代码:

public static void main(String[] args) {
    BufferedReader reader = null;
    ArrayList <String> myFileLines = new ArrayList <String>();

    try {
        String sCurrentLine;
        reader = new BufferedReader(new 
                FileReader("/Users/FakeUsername/Desktop/GroceryList.txt"));
        while ((sCurrentLine = reader.readLine()) != null) {
            System.out.println(sCurrentLine);               
        }
    } catch (IOException e) {
        e.printStackTrace();
        System.out.print(e.getMessage());
    } finally {
        try {
            if (reader != null)reader.close();
        } catch (IOException ex) {
            System.out.println(ex.getMessage());
            ex.printStackTrace();
        }
    }
}

3 个答案:

答案 0 :(得分:0)

使用String的split函数。它根据要与字符串分割的字符返回String的数组。您的情况如下。

 String sCurrentLine = new String();
 reader = new BufferedReader(new 
                FileReader("/Users/FakeUsername/Desktop/GroceryList.txt"));
 while ((sCurrentLine = reader.readLine() != null) {
    String words[] = sCurrentLine.split(" ");
    System.out.println(words[0]+" "+words[1]);
 } 

答案 1 :(得分:0)

Java 8+,您可以使用BufferedReader的{​​{3}}方法很容易地做到这一点:

String filename = "Your filename";
reader = new BufferedReader(new FileReader(fileName));
reader.lines()
      .map(line -> line.split("\\s+")[1])
      .forEach(System.out::println);

输出:

Bananas
Pudding
Soda
Bread

这将在Stream中的所有行中创建一个BufferedReader,在空白处分割每一行,然后获取第二个标记并打印

答案 2 :(得分:-1)

请尝试以下代码-:

outerWhileLoop: 
while ((sCurrentLine = reader.readLine()) != null) {
     //System.out.println(sCurrentLine);
     StringTokenizer st = new StringTokenizer(sCurrentLine," .");
     int cnt = 0;
     while (st.hasMoreTokens()){
        String temp = st.nextToken();
        cnt++;
        if (cnt == 2){
           System.out.println(temp);
           continue outerWhileLoop;  
        }
    }
}