【发布时间】:2016-07-06 18:57:42
【问题描述】:
试图只获取其中包含 1 个单词的行。
当前方法得到了正确的结果,但有时输入文件的每个单词之间的行数超过 4 行。所以需要一种方法来只获取其中包含 1 个单词的行。有什么想法吗?
以下是输入文本的示例:
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)
【问题讨论】:
标签: java string bufferedreader