試圖僅獲取包含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)
謝謝!我給了這個嘗試,但仍然得到描述中的錯誤...任何想法,爲什麼? –
是的,['newBufferedReader()'](https://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html#newBufferedReader-java.nio.file.Path-)以UTF-8讀取文件,該文件可能不是UTF-8,而是系統默認的代碼頁。改爲使用'newBufferedReader(path,Charset.defaultCharset())'。 – Andreas
但是,沒有任何人在這裏建議任何編輯的代碼工作正常。所以這不可能是問題。 –