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

32,736

Solution 1

You can convert in an array of chars.

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();
            }
        }
    }

Solution 2

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();

Solution 3

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

Share:
32,736
Gcap
Author by

Gcap

Updated on November 14, 2020

Comments

  • Gcap
    Gcap over 3 years

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

    Thanks!