java - 仅提取 1 个单词的行?

标签 java string bufferedreader

试图只获取其中包含 1 个单词的行。

当前的方法得到了正确的结果,但有时输入文件的每个单词之间有超过 4 行。所以需要一种方法来只获取其中包含一个单词的行。有什么想法吗?

这是输入文本的示例:

adversary
someone who offers opposition
The students are united by shared suffering, and by a common adversary. 
— New York Times (Nov 10, 2014)
aplomb
great coolness and composure under strain
I wish I had handled it with aplomb. 
— New York Times (May 18, 2014)
apprehensive

所以输出应该是这样的:

adversary
aplomb
apprehensive

目前的代码如下:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.Paths;

public class Process {

    public static void main(String[] args) {

        String fileNameOutput = "OutputFile.txt";
        String fileName = "InputWords";

        try (BufferedReader bReader = Files.newBufferedReader(Paths.get(fileName))){

            PrintWriter outputStream = new PrintWriter(fileNameOutput); 
            int lineNum = 0;
            String line = null;

            while ( (line = bReader.readLine() ) != null ) {
               lineNum++;

             if ( lineNum % 4 == 0 ) continue;


                outputStream.println(line);


            }
                outputStream.close();

        } catch (IOException e) {
            e.printStackTrace();
        }



    }

}

感谢您的宝贵时间。


编辑

根据以下建议的修复从控制台获取此错误。

java.nio.charset.MalformedInputException: Input length = 1
    at java.nio.charset.CoderResult.throwException(Unknown Source)
    at sun.nio.cs.StreamDecoder.implRead(Unknown Source)
    at sun.nio.cs.StreamDecoder.read(Unknown Source)
    at java.io.InputStreamReader.read(Unknown Source)
    at java.io.BufferedReader.fill(Unknown Source)
    at java.io.BufferedReader.readLine(Unknown Source)
    at java.io.BufferedReader.readLine(Unknown Source)
    at Process.main(Process.java:20)

最佳答案

好吧,而不是

if ( lineNum % 4 == 0 ) continue;

条件,你可以简单地检查你刚刚读到的行是否包含多个标记:

if (line.split(" ").length > 1) continue;

if (line.indexOf(" ") >= 0) continue;

后一种情况应该比前一种更有效。

关于java - 仅提取 1 个单词的行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36111187/

相关文章:

java - 评估字符串中的数学表达式

java - 使用 Mockito 运行单元测试时出现 NullPointerException

java - 反编译修复代码后重新编译成*.Jar?

java - 尝试使用 BufferedReader 从 System.in 读取输入并将其放入数组中,但似乎不想给我数组

java - java中获取输入的快速方法有哪些?

java - 驱动器已满或空间不足的 IOException

javascript - 如何在 JavaScript 提示符中将字符串格式化为多行?

无法从 C 中的结构打印字符串

Python Pandas 在 to_datetime 上调试

java - 使用 BufferedReader 将文件内容存储在 Integer 的 ArrayList 中