0

I have a file like this

test.txt:

122352352246

12413514316134

Now I want to read each digit a time, and store it as one element in, say, a list. I tried using Scanner. But it will read a line each time, and outputs a long integer. That means if I want to get the digits, I need to further separate the digits in that integer. I guess there must be an elegant way to directly read one digit each time. Below is my code

public class readDigits {

public static void main(String[] args) throws IOException{
    List<Integer> list = new ArrayList<Integer>();
    File file = new File("test.txt");
    Scanner in = new Scanner(file);
    int c;
    try {
         while (in.hasNext()){
             c = in.nextInt();
             list.add(c);

        }

    }
    finally {
        System.out.println(list);
        in.close();
    }

}


}
zhang_rick
  • 113
  • 1
  • 11

2 Answers2

0

I guess there must be an elegant way to directly read one digit each time.

A digit is a character - so you want to read a single character at a time.

Oddly enough, Scanner doesn't appear to be conducive to that. You could read a byte at a time from Scanner, but it would possibly be better to use a Reader instead:

List<Integer> list = new ArrayList<Integer>();
try (Reader reader = Files.newBufferedReader(Paths.get("test.txt"))) {
    int c;
    while ((c = reader.read()) != -1) {
        char ch = (char) c;
        int value = Character.getNumericValue(ch);
        if (value >= 0) {
            list.add(value);
        }
    }
}
System.out.println(list);

Alternatively, you could read all the lines of the file, and process each line individually - that would be pretty simple too.

Jon Skeet
  • 1,261,211
  • 792
  • 8,724
  • 8,929
0

Try this:

byte[] buffer = new byte[2];
try (InputStream str = new FileInputStream("test.txt")) {
    while (str.read(buffer) != -1) {
        System.out.print(new String(buffer));
    }
}
Halmackenreuter
  • 564
  • 4
  • 8