简体   繁体   中英

How to properly read integer from file in Java

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.

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) {}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM