I'm trying to use scanner to print lines from a text file, but it only prints first line before printing only new lines until while loop goes through file.
String line;
File input = new File("text.txt");
Scanner scan = new Scanner(input);
while (scan.hasNext()) //also does not work with hasNextLine(), but additional error
{
line = scan.nextLine();
System.out.println(line);
//other code can see what is in the string line, but output from System.out.println(line); is just a new line
}
How can I get System.out.println() to work with this code?
This is the Javadoc for nextLine()
Advances this scanner past the current line and returns the input that was skipped. This method returns the rest of the current line, excluding any line separator at the end. The position is set to the beginning of the next line.
You want next() instead:
Finds and returns the next complete token from this scanner. A complete token is preceded and followed by input that matches the delimiter pattern. This method may block while waiting for input to scan, even if a previous invocation of hasNext() returned true.
Your code becomes:
while (scan.hasNext())
{
line = scan.next();
System.out.println(line);
}
You may use .next() method:
String line;
File input = new File("text.txt");
Scanner scan = new Scanner(input);
while (scan.hasNext()) //also does not work with hasNextLine(), but additional error
{
line = scan.next();
System.out.println(line);
}
Related
I am trying to read a log file word by word using a scanner and using the code
Scanner scanner = new Scanner(file);
while(scanner.hasNext()){
String word = scanner.next();
}
But the problem is that this stops after it reaches the end of the file but I need to read it as it gets generated
I tried this to solve this using the below code
Scanner scanner = new Scanner(file);
while(true){
while(!scanner.hasNext()){
Thread.sleep(1000);
}
String word = scanner.next();
}
But the code does not seem to work and gets stuck in the while loop even when the log file has more data appended to it.
Can someone point out what i am doing wrong.
I made an small snippet for reading a log file for another system. I used BufferedReader instead of Scanner. Because it will run until the end of file and still reading. Instead of using the Scanner Next.
readLine() Doc:
* #return A String containing the contents of the line, not including
* any line-termination characters, or null if the end of the
* stream has been reached
And My Snippet
BufferedReader br = new BufferedReader(new InputStreamReader(file));
while (true)
{
strLine = br.readLine();
if(strLine!=null)
{
System.out.println(strLine);
}else{
Thread.sleep(100);
}
}
I wrote a .txt file in which each line has a meaning - even an empty one. Scanner's methods next() and nextLine() do not recognize the empty line and jump right to the line with text. I'm wondering if there is a way for the scanner to consider all lines of text regardless the content.
I don't want to use BufferedReader because I'm working with very small tokens each time.
static final String fileName = "temp.txt";
try {
//System.out.println(Jsoup.connect(url).get());
Document document = Jsoup.connect(url).get();
FileWriter fileWriter = new FileWriter(fileName);
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
Elements names = document.select("[id^=CZ]");
for (Element name : names) {
bufferedWriter.write(name.text());
bufferedWriter.write(System.lineSeparator() + System.lineSeparator());
System.out.println(name.text() + '\n');
}
bufferedWriter.close();
Scanner in = new Scanner(new File(fileName));
in.next();
String s = names.first().text();
String h = in.next();
...
At this point Strings s & h should be equal.
The document the scanner is reading starts with an empty line and goes like this:
asdkjasjkdajkdahkdjahdjadhkahdajkdajkdsasdkjasjkdajkdahkdjahdjadhkahdajkdajkdsasdkjasjkdajkdahkdjahdjadhkahdajkdajkdsasdkjasjkdajkdahkdjahdjadhkahdajkdajkdsasdkjasjkdajkdahkdjahdjadhkahdajkdajkdsasdkjasjkdajkdahkdjahdjadhkahdajkdajkdsasdkjasjkdajkdahkdjahdjadhkahdajkdajkdsasdkjasjkdajkdahkdjahdjadhkahdajkdajkdsasdkjasjkdajkdahkdjahdjadhkahdajkdajkdsasdkjasjkdajkdahkdjahdjadhkahdajkdajkdsasdkjasjkdajkdahkdjahdjadhkahdajkdajkdsasdkjasjkdajkdahkdjahdjadhkahdajkdajkds
Again, I have a dynamic file that might have first line empty and when I compare String s with String h they DO NOT equal. nextLine() and next() skip over the first line while it is still a valid element.
nextLine() is the method that you need. Unlinke next(), it does not skip ahead through newlines and white space.
Run this example (demo)
Scanner sc = new Scanner(System.in);
while (sc.hasNextLine()) {
String s = sc.nextLine();
System.out.println("'"+s+"'");
}
on input with empty lines to see that these lines are preserved:
'quick brown'
''
'fox jumps'
'over'
''
'the'
''
'lazy dog'
next() method reads tokens seperated by whitespaces or newline characters on other hand nextLine() reads lines seperated by newline charater.
You can try this:
Scanner scan = new Scanner(file);
while(scan.hasNextLine()){
System.out.println(scan.nextLine());
}
I'm reading from System.in, and I'm using the Scanner class. My problem is when I use redirection the last line in the file is not being read. I read the documentation for Scanner.readLine, and I'm guessing it's because it does not have a "end of line" character. Any idea what I can use instead to get this last line?
In my code input is "".
Scanner scanner = new Scanner(System.in);
int sizeOfList = scanner.nextInt();
ArrayList<Integer> arrayList = new ArrayList<Integer>();
String input = scanner.nextLine();
System.out.println(input);
String[] splitInput = input.split(" |\\n");
for(int i = 0; i < splitInput.length; i++)
{
System.out.println(splitInput[i]);
arrayList.add(new Integer(Integer.parseInt(splitInput[i])));
}
instead of scanner.nextLine(), you could use scanner.next() .... This will get a string from the scanner when it does not have an end of line character.
You can also call scanner.hasNextLine() to check if you have reached the line at the end that you are worried about!
Here's the code:
BufferedReader in= new BufferedReader(new FileReader("C:\\Users\\ASUS\\Desktop\\123.txt"));
Scanner scanner= new Scanner(in);
while((scanner.findInLine("abc"))!=null){
if(scanner.hasNext()){
System.out.println(scanner.next());
}
}
findInLine only searches the first line not the others. So it prints nothing.
How can i fix this problem?
You should be looping over all the lines - and then if the line matches, then print it out (or whatever). For example:
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
// Now check the line, and do whatever you need.
}
Or you could still use findInLine, just explicitly calling nextLine as well:
while (scanner.hasNextLine()) {
if (scanner.findInLine(...)) {
...
}
// Read to the end of the line whether we found something or not
scanner.nextLine();
}
I am trying to split a paragraph of text into separate sentences based on punctuation marks i.e. [.?!] However, the scanner splits the lines at the end of each new line as well, even though I've specified a particular pattern. How do I resolve this? Thanks!
this is a text file. yes the
deliminator works
no it does not. why not?
Scanner scanner = new Scanner(fileInputStream);
scanner.useDelimiter("[.?!]");
while (scanner.hasNext()) {
line = scanner.next();
System.out.println(line);
}
I don't believe the scanner splits it on line breaks, it is just your "line" variables have line breaks in them and that is why you get that output. For example, you can replace those line breaks with spaces:
(I am reading the same input text you supplied from a file, so it has some extra file reading code, but you'll get the picture.)
try {
File file = new File("assets/test.txt");
Scanner scanner = new Scanner(file);
scanner.useDelimiter("[.?!]");
while (scanner.hasNext()) {
String sentence = scanner.next();
sentence = sentence.replaceAll("\\r?\\n", " ");
// uncomment for nicer output
//line = line.trim();
System.out.println(sentence);
}
scanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
This is the result:
this is a text file
yes the deliminator works no it does not
why not
And if I uncomment the trim line, it's a bit nicer:
this is a text file
yes the deliminator works no it does not
why not