I am trying to check whether I have reached the last line in the text document to write a simple line in the text document.
I have tried the following code below but I am getting this error:
Exception in thread "main" java.util.NoSuchElementException: No line found
I have text in hello.txt
document so I dont understand what this error mean.
How can I fix that?
I appreciate any help.
Code:
public static void main(String[] args) {
try (PrintWriter writer = new PrintWriter("D:\\hl_sv\\hello2.txt");
Scanner scanner = new Scanner("D:\\hl_sv\\hello.txt")) {
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
// In the case the line is the last one and there is no number.
// The content of the arrayList must be printed.
if ((line = scanner.nextLine()).isEmpty()) {
System.out.println("last line in the text document");
writer.write("last line in the text document.");
}
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Edit
public static void main(String[] args) {
try (PrintWriter writer = new PrintWriter("D:\\hl_sv\\hello2.txt");
Scanner scanner = new Scanner("D:\\hl_sv\\hello.txt")) {
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
// In the case the line is the last one and there is no number.
// The content of the arrayList must be printed.
if (line.isEmpty()) { // <-- Removed = scanner.nextLine()
System.out.println("last line in the text document");
writer.write("last line in the text document.");
}else{
writer.write(line);
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
With the edit code I am not getting the error anymore but I am getting this D:\hl_sv\hello.txt
line printed in the text document hello2.txt
?