Reading text using Java next scanner (template template)

I am trying to use the Scanner class to read a string, using the following (boilerplate) method to grab the text before the colon, and then after the colon, to s1 = textbeforecolon and s2 = textaftercolon.

The line looks like this:

something: somethingelse

+3
source share
3 answers

There are two ways to do this, depending on what you want.

If you want to separate all input into a colon, you can use the method useDelimiter(), as others have pointed out:

// You could also say "scanner.useDelimiter(Pattern.compile(":"))", but
// that the exact same thing as saying "scanner.useDelimiter(":")".
scanner.useDelimiter(":");

// Examines each token one at a time
while (scanner.hasNext())
{
    String token = scanner.next();
    // Do something with token here...
}

If you want to separate each line with a colon, then it would be much easier to use the method String split():

while (scanner.hasNextLine())
{
    String[] parts = scanner.nextLine().split(":");
    // The parts array now contains ["something", "somethingelse"]
}
+10
source
File file = new File("someFileWithLinesContainingYourExampleText.txt");
Scanner s = new Scanner(file);
s.useDelimiter(":");

while (!s.hasNextLine()) {
    while (s.hasNext()) {
        String text = s.next();
    System.out.println(text);
    }

    s.nextLine();
}
0
source

Source: https://habr.com/ru/post/1707988/


All Articles