How to read an input file char by char using a Sca

2019-04-26 15:43发布

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

Thanks!

标签: java input io
4条回答
倾城 Initia
2楼-- · 2019-04-26 16:02

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();
查看更多
ら.Afraid
3楼-- · 2019-04-26 16:03

If you're committed to using Scanner then you can use next(String pattern).

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

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

查看更多
Explosion°爆炸
4楼-- · 2019-04-26 16:05

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

查看更多
霸刀☆藐视天下
5楼-- · 2019-04-26 16:17

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();
            }
        }
    }
查看更多
登录 后发表回答