How to read char input file to char using scanner?

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

Thanks!

+7
source share
4 answers

You can convert to an array of characters.

 import java.io.*; import java.util.Scanner; public class ScanXan { public static void main(String[] args) throws IOException { Scanner s = null; try { s = new Scanner(new BufferedReader(new FileReader("yourFile.txt"))); while (s.hasNext()) { String str = s.next(); char[] myChar = str.toCharArray(); // do something } } finally { if (s != null) { s.close(); } } } 
+2
source

If you need to use Scanner (as you noted in your editing), try the following:

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

Now myScanner should read character by character.


Instead, you can use the BufferedReader (if you can) - it has a read that reads one character. For example, 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(); 
+6
source

Split the string into characters using String.toCharArray() .

+2
source

If you intend to use Scanner , you can use next(String pattern) .

 String character = scanner.next("."); 

The above returns a String length 1 - that is, you get a character, but as a string.

0
source

All Articles