I have searched similar questions, but none helped.
Consider a file :
hi how are you?
where were you?
I want to do few operations after the end of every line. If I use next()
it wont tell me when I have reached the end of the first line.
Also I have seen hasNextLine()
but it only tells me if there exists another line or not.
Consider using more than one Scanner, one to get each line, and the other to scan through each line after you've received it. The only caveat I must give is that you must be sure to close the inner Scanner after you're done using it. Actually you will need to close all Scanners after you're done using them, but especially the inner Scanners since they can add up and waste resources.
e.g.,
Scanner fileScanner = new Scanner(myFile);
while (fileScanner.hasNextLine()) {
String line = fileScanner.nextLine();
Scanner lineScanner = new Scanner(line);
while (lineScanner.hasNext()) {
String token = lineScanner.next();
// do whatever needs to be done with token
}
lineScanner.close();
// you're at the end of the line here. Do what you have to do.
}
fileScanner.close();
You can scan the text line by line and split each line in tokens using String.split()
method. This way you know when one line has ended and also have all the tokens on each line:
Scanner sc = new Scanner(input);
while (sc.hasNextLine()){
String line = sc.nextLine();
if (line.isEmpty())
continue;
// do whatever processing at the end of each line
String[] tokens = line.split("\\s");
for (String token : tokens) {
if (token.isEmpty())
continue;
// do whatever processing for each token
}
}
Not sure if this is relevant or too late when i read this. I am relatively new to Java but this seemed to work for me when i encountered a similar problem. I just used a DO-WHILE loop with a End of file specifier denoted by a simple string.
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;`enter code here`
public class Main {
public static void main(String[] args) {
List<String> name = new ArrayList<>();
Scanner input = new Scanner(System.in);
String eof = "";
do {
String in = input.nextLine();
name.add(in);
eof = input.findInLine("//");
} while (eof == null);
System.out.println(name);
}
}
You can use Scanner and the method you mentioned:
Scanner scanner = new Scanner(new File("your_file"));
while(scanner.hasNextLine()){
String line = scanner.nextLine();
// do your things here
}
来源:https://stackoverflow.com/questions/15183761/how-to-check-the-end-of-line-using-scanner