很难从每一行中得到第一个单词。有什么想法为什么要输出空白文件?
该程序将以下文本作为输入:
abecedism word created from the initials of words in a phrase
ablaut variation in root vowel of words to change meaning
acronym word formed from initial letters of another word
acrophonic using a symbol for the initial sound of a thing
acroteleutic phrase or words at the end of a psalm
adversative word or phrase expressing opposition
目的是使结果看起来像这样:
abecedism
ablaut
acronym
acrophonic
acroteleutic
adversative
这是到目前为止的代码:
public static void main(String args[]) {
String fileNameOutput = "OutputFile.txt";
String fileName = "InputWords.txt";
Charset cs = Charset.defaultCharset();
try (BufferedReader bReader = Files.newBufferedReader(Paths.get(fileName), cs)) {
PrintWriter outputStream = new PrintWriter(fileNameOutput);
int lineNum = 0;
String line = null;
while ((line = bReader.readLine()) != null) {
lineNum++;
if (line.split(" ").length > 1) continue;
outputStream.println(line);
}
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (line.split(" ").length > 1) continue;
检查行中是否包含一个以上的单词/标记,如果行包含多个单词/标记,则立即开始新的迭代,这意味着您将跳过其余代码,continue
这将阻止您执行
outputStream.println(line);
并且由于文件中的每一行都包含一个以上的单词,因此您无需在结果文件中添加任何内容。
使用Scanner类可以使您的代码稍微简化一些,该类允许我们使用next()
method遍历单词/标记。
try (Scanner sc = new Scanner(new File(fileName));
PrintWriter outputStream = new PrintWriter(fileNameOutput);) {
while (sc.hasNextLine()) {
outputStream.println(sc.next());// write first word from line
sc.nextLine();// consume rest of text from that line
}
} catch (IOException e) {
e.printStackTrace();
}
注意:请勿close()
在“尝试”部分中调用。如果有些异常会发生outputStream.close();
你PrintWriter outputStream
就不叫这可能使很多问题。您应该将可关闭资源的声明移动为try-with-resources的一部分。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句