java - 如何在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新手,如果答案很明显,很抱歉!)
解决方案
换行
inFS = new Scanner(fileByteStream);
经过
inFS = new Scanner(fileByteStream).useDelimiter( "\\n" );
这会将“单词”分隔符设置为换行符,使整行成为单个“单词”。
或者使用java.nio.files.Files.lines()
……</p>
也是java.io.BufferedReader.lines()
一个不错的选择……</p>
推荐阅读
- c# - 在 C# 中将矩阵分配给 [] 数组 Matrix
- qt - QT5.10.1 找不到服务 - Window 上的“org.qt-project.qt.mediaplayer”
- ruby-on-rails - 为什么我会收到这个未初始化的常量错误?
- r - 如何根据 R 中另一列中的特定文本创建二进制列?
- java - Netbeans 8.2 无法验证 Git 凭证?
- c++ - cin.rdstate() 返回什么?
- php - 在 STR 上将 STR 的其余部分替换为 0
- python - 空间 | 是否可以删除短语匹配器中对长度的硬编码限制?
- c++ - 为什么我不能发送 PostMessage?
- css - 如何创建多色边框?