Reputation: 41
I have read previous posts and tryed to integrate code in to my project. I am trying to read integers from my txt file. I am using this method:
static Object[] readFile(String fileName) throws FileNotFoundException {
Scanner scanner = new Scanner(new File(fileName));
List<Integer> tall = new ArrayList<Integer>();
while (scanner.hasNextInt()) {
tall.add(scanner.nextInt());
}
return tall.toArray();
}
I don't know the size of data, so i am using List in main calling method:
Object [] arr = readFile("C:\\02.txt");
System.out.println(arr.length);
I am getting that the array size is 0; The integers i am trying to read from the file is binary Sequence. (1010101010...) I thought that the problem is connected with scanner maybe he thinks that it is not the integer.
Upvotes: 0
Views: 163
Reputation: 7457
You can use BufferReader
instead :
String line = "";
List<Integer> tall = new ArrayList<Integer>();
try {
BufferedReader br = new BufferedReader(new FileReader(fileName));
while ((line = br.readLine())!= null) {
tall.add(Integer.parseInt(line, 2));
}
br.close();
}catch(IOException e) {}
Upvotes: 1
Reputation: 124215
If you are reading data in binary form then consider using nextInt
or hasNextInt
with radix.
while (scanner.hasNextInt(2)) {
tall.add(scanner.nextInt(2));
}
Otherwise you will be reading integers as decimals so values may be out of integers range like in case of
11111111111111111111111111111111
Upvotes: 0