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

0

6 Answers 6

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

Sign up to request clarification or add additional context in comments.

3 Comments

You are using the same answer that is answered here
I've added the required citations to your answer. Please make sure to do that in the future.
File file = new File("tall.txt"); Scanner scanner = new Scanner(file); List<Integer> integers = new ArrayList<>(); while (scanner.hasNext()) { if (scanner.hasNextInt()) { integers.add(scanner.nextInt()); } else { scanner.next(); } } System.out.println(integers);
4

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

1 Comment

+1 I would use nextLong() as 34234324234 is too large for an int
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();
}

Comments

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.

Comments

1

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

3 Comments

I'd not found readLine() in FileInputStrem
what @MohammadFaisal said
@Mr_and_Mrs_D mohammad asked the right question, the readline() method is not present in FileInputStream but it is in BufferedReader. Moreover, FileInputStrem.read() method returns only types int char byte`
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();
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.