How to read integer values ​​from a text file

Possible duplicate:
Java: reading integers from file to array

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

12345 3456778 234234234 34234324234 

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

+6
source share
6 answers

You might want to do something like this (if you are using java 5 or 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 of Reading Integers from a File in an Array

+14
source

You can use Scanner and nextInt() . The scanner also has nextLong() for large integers.

+3
source

Try the following: -

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

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

>
+2
source

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

There is a scanner for Java 5 or 4, but BigInteger support is not supported. You must read line by line (using the readLine of the Scanner class) and create a BigInteger object from line.

+1
source

I would use almost the same, but with a list as a buffer for 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(); } 
0
source

Source: https://habr.com/ru/post/916642/


All Articles