Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read an input file char by char using a Scanner?

Tags:

java

io

input

I have to use Scanner, so is there a nextChar() instead of nextLine() method that I could use?

Thanks!

like image 759
Gcap Avatar asked Nov 13 '12 22:11

Gcap


People also ask

How do you scan a char input?

To take a char input using Scanner and next(), you can use these two lines of code. Scanner input = new Scanner (system.in); char a = input. next().

Can you use Scanner to read a file?

Reading the contents of a file − To read the contents of a file, Scanner class provides various constructors. Used to read data from the file represented by the given File object. Used to read data from the specified InputStream.

Can a Scanner read from a string?

Scanner is simple text scanner which can parse primitive types and strings using regular expressions. So, passing System.in to Scanner allows us to parse or read string from standard input stream, which is console.


1 Answers

If you have to use a Scanner (as you noted in your edit), try this:

myScanner.useDelimiter("(?<=.)");

Now myScanner should read character by character.


You might want to use a BufferedReader instead (if you can) - it has a read method that reads a single character. For instance, this will read and print the first character of your file:

BufferedReader br = new BufferedReader(new FileReader("somefile.txt"));
System.out.println((char)br.read());
br.close();
like image 117
arshajii Avatar answered Nov 16 '22 01:11

arshajii