如何在 java 中打印整行文本(来自输入文件)

How to print a full line of text in java (from input file)

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

  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 文件是这样的: 这是第一行。 (换行)这是第二行。 (换行)这是第三行。 ...

然后现在打印如下: 这个 (新行)IS (新线)THE (新行)第一 (新线)线 (新行)这个 (新行)IS ...

我希望它像在原始文件中那样打印。

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

要读取文件,您需要 BufferedReader:

Reads text from a character-input stream, buffering characters so as to provide for the efficient reading of characters, arrays, and lines.

然后使用它的方法readLine:

Reads a line of text. A line is considered to be terminated by any one of a line feed ('\n'), a carriage return ('\r'), or a carriage return followed immediately by a linefeed.

此代码读取文件的每一行然后打印它:

try (BufferedReader br = new BufferedReader(new FileReader(new File(filePath)))) {
  while ((line = br.readLine()) != null) {
    System.out.println(line);
  }
}

替换行

inFS = new Scanner(fileByteStream);

来自

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

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

或使用java.nio.files.Files.lines()

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

更简单、更清晰的方法是:

FileInputStream fis = new FileInputStream("filename");
Scanner sc = new Scanner(fis);
while (sc.hasNextLine()) {
    System.out.println(sc.nextLine());
}

BufferedReader br = new BufferedReader(new FileReader("filename"));
br.lines().forEach(System.out::println);