I'm trying to print each individual line of an external file, but I can only manage to print each individual word. Here's what my code currently looks like:
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);
}
So, for example, if the external .txt file is something like this: THIS IS THE FIRST LINE. (new line) THIS IS THE SECOND LINE. (new line) THIS IS THE THIRD LINE. ...
Then right now it prints like this: THIS (new line) IS (new line) THE (new line) FIRST (new line) LINE (new line) THIS (new line) IS ...
and I want it to print like how it appears in the original file.
Any suggestions on how to make each iteration of resultToPrint be a full line of text, as opposed to a single word? (I'm new to java, so sorry if the answer seems obvious!)
CodePudding user response:
In order to read a file you need a BufferedReader:
Reads text from a character-input stream, buffering characters so as to provide for the efficient reading of characters, arrays, and lines.
Then use it's method 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.
This code reads every line of a file then prints it:
try (BufferedReader br = new BufferedReader(new FileReader(new File(filePath)))) {
while ((line = br.readLine()) != null) {
System.out.println(line);
}
}
CodePudding user response:
Replace the line
inFS = new Scanner(fileByteStream);
by
inFS = new Scanner(fileByteStream).useDelimiter( "\\n" );
This will set the "word" separator to the line feed character, making the full line a single "word".
Or use java.nio.files.Files.lines()
…
Also java.io.BufferedReader.lines()
would be a nice alternative …
CodePudding user response:
Simpler and cleaner approach would be:
FileInputStream fis = new FileInputStream("filename");
Scanner sc = new Scanner(fis);
while (sc.hasNextLine()) {
System.out.println(sc.nextLine());
}
or
BufferedReader br = new BufferedReader(new FileReader("filename"));
br.lines().forEach(System.out::println);