📘 Premium Read: Access my best content on Medium member-only articles — deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.
🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (176K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
The useDelimiter()
method in Java, part of the java.util.Scanner
class, is used to set a custom delimiter pattern for the Scanner
. This method is useful when you need to parse input data with delimiters other than the default whitespace.
Table of Contents
- Introduction
useDelimiter()
Method Syntax- Understanding
useDelimiter()
- Examples
- Basic Usage
- Using Regular Expressions
- Real-World Use Case
- Conclusion
Introduction
The useDelimiter()
method allows you to specify a custom delimiter pattern that the Scanner
will use to tokenize the input. By default, the Scanner
uses whitespace as the delimiter. This method can be useful for parsing data that is separated by other characters, such as commas or semicolons.
useDelimiter() Method Syntax
There are two overloaded versions of the useDelimiter()
method:
Using a String Pattern
public Scanner useDelimiter(String pattern)
Using a Pattern Object
public Scanner useDelimiter(Pattern pattern)
Parameters:
pattern
: The delimiter pattern, either as aString
orPattern
object.
Returns:
- The
Scanner
object, to allow method chaining.
Throws:
IllegalArgumentException
: If the specified pattern is invalid.IllegalStateException
: If the scanner is closed.
Understanding useDelimiter()
The useDelimiter()
method sets the delimiter pattern that the Scanner
will use to tokenize the input. This method returns the Scanner
object itself, enabling method chaining. The delimiter pattern can be specified as a regular expression string or a Pattern
object.
Examples
Basic Usage
To demonstrate the basic usage of useDelimiter()
, we will create a Scanner
object and set a custom delimiter.
Example
import java.util.Scanner; public class UseDelimiterExample { public static void main(String[] args) { String input = "apple,banana,cherry"; // Create Scanner object in try-with-resources to ensure it closes automatically try (Scanner scanner = new Scanner(input)) { scanner.useDelimiter(","); // Set comma as the delimiter while (scanner.hasNext()) { String token = scanner.next(); System.out.println("Token: " + token); } } // Scanner is automatically closed here } }
Output:
Token: apple Token: banana Token: cherry
Using Regular Expressions
This example shows how to use a regular expression as a delimiter to handle more complex tokenization.
Example
import java.util.Scanner; import java.util.regex.Pattern; public class UseDelimiterRegexExample { public static void main(String[] args) { String input = "apple, banana; cherry: date"; // Create Scanner object in try-with-resources to ensure it closes automatically try (Scanner scanner = new Scanner(input)) { scanner.useDelimiter("[,;: ]+"); // Set multiple delimiters while (scanner.hasNext()) { String token = scanner.next(); System.out.println("Token: " + token); } } // Scanner is automatically closed here } }
Output:
Token: apple Token: banana Token: cherry Token: date
Real-World Use Case
Parsing a Log File
In real-world applications, the useDelimiter()
method can be used to parse log files where entries are separated by a specific delimiter.
Example
import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class LogFileParser { public static void main(String[] args) { File file = new File("log.txt"); try (Scanner scanner = new Scanner(file)) { scanner.useDelimiter("\\|"); // Use pipe character as delimiter while (scanner.hasNext()) { String logEntry = scanner.next(); System.out.println("Log entry: " + logEntry); } } catch (FileNotFoundException e) { System.out.println("File not found: " + e.getMessage()); } // Scanner is automatically closed here } }
Output (Assuming log.txt
contains pipe-separated log entries):
Log entry: INFO: Application started Log entry: WARN: Low memory Log entry: ERROR: Null pointer exception ...
Conclusion
The Scanner.useDelimiter()
method is used to set a custom delimiter pattern for tokenizing input data. This method is particularly useful for parsing data separated by characters other than whitespace. By understanding and using this method, you can efficiently parse and handle input data with custom delimiters. Always close the Scanner
using try-with-resources to ensure proper resource management.
Comments
Post a Comment
Leave Comment