我试图打印每个单独的行外部文件,但我只能打印每个单独的字。下面是我的代码当前的样子:
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…
,我想让它打印出来,就像它在原始文件中的样子
关于如何使resulttopprint的每次迭代是一整行文本,而不是一个单词的任何建议?(我是java新手,很抱歉,如果答案看起来很明显!)
替换行
inFS = new Scanner(fileByteStream);
inFS = new Scanner(fileByteStream).useDelimiter( "\n" );
这将设置"word"分隔符加到换行符上,使整行变成一个单独的"word"
或者使用java.nio.files.Files.lines()
…
java.io.BufferedReader.lines()
也是一个不错的选择…
为了读取文件,您需要BufferedReader:
然后使用它的方法readLine:从字符输入流中读取文本,缓冲字符,以便有效地读取字符、数组和行。
读取一行文本。一条线被认为是终止的任何一个换行(" n"),回车( r),或回车跟随换行符。
这段代码读取文件的每一行,然后打印出来:
try (BufferedReader br = new BufferedReader(new FileReader(new File(filePath)))) {
while ((line = br.readLine()) != null) {
System.out.println(line);
}
}
更简单明了的方法是:
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);