java.util.Scanner useDelimiter(String pattern)

Description :

This java tutorial shows how to use the useDelimiter(String pattern) method of Scanner class of java.util package. This method sets the delimiter String to be used by the Scanner object. This method is a shortcut in invoking useDelimiter(Pattern.compile(pattern)).

Method Syntax :

public Pattern delimiter()

Parameter Input :

 

DataType Parameter Description
String pattern The pattern to be used by the Scanner object

 

Method Returns :

This method simply returns this Scanner object.

Compatibility Version :

Requires Java 1.5 and up

Exception :

None

Discussion :

The usedelimiter(String pattern) method sets the delimiter of this Scanner object. This delimiter will be used by scanner object to tokenize string. This is helpful if we are using Scanner to split String into multiple tokens.

This method is necessary specially in dealing with files as a data source. I have used this method a lot in splitting delimited strings coming from flat files. Legacy systems usually saves it’s data in files separated only with string patterns to separate the fields.

One good example on the usage of this method is in parsing csv files. CSV files are usually delimited with line break per row and semicolon(;) for columns. Thus the use of useDelimiter(String pattern) will be helpful on this scenario.

Java Code Example :

This java example source code demonstrates the use of useDelimiter(String pattern) method of Scanner class. Basically we have used the String  semicolon(;) to tokenize the String declared on the constructor of Scanner object.

There are three possible token on the String “Anne Mills/Female/18″ which is name,gender and age. The scanner class is used to split the String and output the tokens in the console.

package com.javatutorialhq.java.tutorial.scanner;

import java.util.Scanner;

/*
 * This is a java example source code that shows how to use useDelimiter(String pattern)
 * method of Scanner class. We use the string ; as delimiter
 * to use in tokenizing a String input declared in Scanner constructor
 */

public class ScannerUseDelimiterDemo {

	public static void main(String[] args) {

		// Initialize Scanner object
		Scanner scan = new Scanner("Anna Mills/Female/18");
		// initialize the string delimiter
		scan.useDelimiter("/");
		// Printing the delimiter used
		System.out.println("The delimiter use is "+scan.delimiter());
		// Printing the tokenized Strings
		while(scan.hasNext()){
			System.out.println(scan.next());
		}
		// closing the scanner stream
		scan.close();

	}

}

Sample Output :

Running the useDelimiter(String patter) method example source code of Scanner class will give you the following output

java scanner usedelimiter(string pattern) method example

java scanner usedelimiter(string pattern) method example

Exception Scenario :

N/A

Similar Method :

  • N/A

Suggested Reading List :

References :