首页 > 解决方案 > 如何在java中打印整行文本(来自输入文件)

问题描述

我正在尝试打印外部文件的每一,但我只能设法打印每个单独的单词。这是我的代码目前的样子:

  Scanner scnr = new Scanner(System.in);
  System.out.println("Enter input filename: ");
  String inputFile = scnr.next();
  
  FileInputStream fileByteStream = null;
  Scanner inFS = null; 
  
  fileByteStream = new FileInputStream(inputFile);
  inFS = new Scanner(fileByteStream);
  
  while (inFS.hasNext()) {
     String resultToPrint = inFS.next();
     System.out.println(resultToPrint);
  }

因此,例如,如果外部 .txt 文件是这样的:这是第一行。(新行)这是第二行。(新行)这是第三行。...

然后现在它打印如下: THIS (new line) IS (new line) THE (new line) FIRST (new line) LINE (new line) THIS (new line) IS ...

我希望它像原始文件中的样子一样打印。

关于如何使 resultToPrint 的每次迭代成为整行文本而不是单个单词的任何建议?(我是java新手,如果答案很明显,很抱歉!)

标签: javastringinputprintingnewline

解决方案


换行

inFS = new Scanner(fileByteStream);

经过

inFS = new Scanner(fileByteStream).useDelimiter( "\\n" );

这会将“单词”分隔符设置为换行符,使整行成为单个“单词”。

或者使用java.nio.files.Files.lines()……</p>

也是java.io.BufferedReader.lines()一个不错的选择……</p>


推荐阅读