12

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

Community
  • 1
  • 1
Cindrella
  • 1,671
  • 7
  • 27
  • 47

6 Answers6

23

You might want to do something like this (if you're using java 5 and more)

Scanner scanner = new Scanner(new File("tall.txt"));
int [] tall = new int [100];
int i = 0;
while(scanner.hasNextInt())
{
     tall[i++] = scanner.nextInt();
}

Via Julian Grenier from Reading Integers From A File In An Array

Community
  • 1
  • 1
Vicky
  • 1,215
  • 6
  • 22
  • 45
  • 2
    You are using the same answer that is answered [here](http://stackoverflow.com/questions/303913/java-reading-integers-from-a-file-into-an-array/304061#304061) – Jainendra May 25 '12 at 10:22
  • 3
    I've added the required citations to your answer. Please make sure to do that in the future. – Tim Post Feb 04 '13 at 11:30
  • File file = new File("tall.txt"); Scanner scanner = new Scanner(file); List integers = new ArrayList<>(); while (scanner.hasNext()) { if (scanner.hasNextInt()) { integers.add(scanner.nextInt()); } else { scanner.next(); } } System.out.println(integers); – Ban Oct 03 '17 at 06:29
4

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

amit
  • 175,853
  • 27
  • 231
  • 333
3

Try this:-

File file = new File("contactids.txt");
Scanner scanner = new Scanner(file);
while(scanner.hasNextLong())
{
  // Read values here like long input = scanner.nextLong();
}
Jainendra
  • 24,713
  • 30
  • 122
  • 169
1

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.

nhahtdh
  • 55,989
  • 15
  • 126
  • 162
1

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

Chandra Sekhar
  • 18,914
  • 16
  • 84
  • 125
1

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();
}
user524029
  • 11
  • 2