[java] How to read integer values from text file

Possible Duplicate:
Java: Reading integers from a file into an array

I want to read integer values from a text file say contactids.txt. in the file i have values like

12345
3456778
234234234
34234324234

i Want to read them from a text file...please help

This question is related to java

The answer is


Try this:-

File file = new File("contactids.txt");
Scanner scanner = new Scanner(file);
while(scanner.hasNextLong())
{
  // Read values here like long input = scanner.nextLong();
}

You can use a Scanner and its nextInt() method.
Scanner also has nextLong() for larger integers, if needed.


use FileInputStream's readLine() method to read and parse the returned String to int using Integer.parseInt() method.


How large are the values? Java 6 has Scanner class that can read anything from int (32 bit), long (64-bit) to BigInteger (arbitrary big integer).

For Java 5 or 4, Scanner is there, but no support for BigInteger. You have to read line by line (with readLine of Scanner class) and create BigInteger object from the String.


I would use nearly the same way but with list as buffer for read integers:

static Object[] readFile(String fileName) {
    Scanner scanner = new Scanner(new File(fileName));
    List<Integer> tall = new ArrayList<Integer>();
    while (scanner.hasNextInt()) {
        tall.add(scanner.nextInt());
    }

    return tall.toArray();
}