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();
}
}
}
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.
See more on this question at Stackoverflow