'How can I make it so my program, for each word read in a string, also reads the following word?

I want my Java program to do the following thing: Whenever it reads a file like the following

Bob went to the store to buy apples.

To read each word in the string (delimited by only a single space character) and to also read the next word, but without "moving" the main reader as well. So it would do something like this:

for word in string{
     print word + nextWord;
}

And its output would be

Bob went
went to
to the
the store
store to
to buy
buy apples.

Edit: IMPORTANT! I don't want to read the whole file and load it into memory. I want this operation to happen DIRECTLY on the file. Imagine I am dealing with something huge, like a whole book, or more.



Solution 1:[1]

No. Scanner doesn't let you peek at future input.

However, it's trivial to code:

Scanner s = new Scanner(new FileInputStream("myfile.txt");
String previous = s.next();
while (s.hasNext()) {
    String next = s.next();
    System.out.println(previous + " " + next);
    previous = next;
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Bohemian