试图只获取其中包含 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/