Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass a CharSequence to a Scanner in Java

The Scanner class has a constructor taking a String.

Scanner s = new Scanner( myString ) ;

How to feed a CharSequence object to a new Scanner? I could first generate a String from the CharSequence, but that is inefficient and rather silly.

Scanner s = new Scanner( myCharSequence.toString() ) ;  // Workaround, but seems needlessly inefficient to instantiate a `String`. 

I looking for a way to access the CharSequence directly from the Scanner. Something like this:

Scanner s = new Scanner( myCharSequence ) ;  // Use `CharSequence` directly.

The Scanner class also takes a Readable in a constructor. Can a CharSequence be presented as a Readable? Or is there some other workaround?

like image 496
Basil Bourque Avatar asked Jun 14 '26 08:06

Basil Bourque


1 Answers

Given that the constructors only accept String and not the more generic CharSequence, you...can't. Not unless you invoke toString on the CharSequence, anyway, which would get you a String back, which would satisfy the constructor's requirements.

So, the workaround calling CharSequence::toString as seen in the Question is indeed the way to go:

new Scanner( myCharSequence.toString() ) 
like image 126
Makoto Avatar answered Jun 16 '26 23:06

Makoto