Reading integer values from a txt file and save them into an array

Z

zigbeedeep

Hello,

I would like to read integer values from a txt file :

sam.txt

66 78 99 90
23 34 56 78
12 45 78 09

and save them into an array

Sam
 
D

Dan Andrews

Hello,

I would like to read integer values from a txt file :

sam.txt

66 78 99 90
23 34 56 78
12 45 78 09

and save them into an array

Sam

Hi Sam,

The cool thing about many of the Reader and Stream objects in the
java.io package is that you can chain them together for the desired
results. Try something like this:

public static List<Integer> getIntegersFromFile(
String fileName) throws IOException {
StringWriter writer = new StringWriter();
BufferedReader reader = new BufferedReader(
new FileReader(fileName));
for (String line = reader.readLine(); line != null; line = reader
.readLine()) {
writer.write(line + " ");
}
StringTokenizer tokens = new StringTokenizer(writer
.toString());
List<Integer> list = new ArrayList<Integer>();
while (tokens.hasMoreTokens()) {
String str = tokens.nextToken();
try {
list.add(new Integer(str));
} catch (NumberFormatException e) {
System.out.println("Error '" + str
+ "' is not an integer.");
}
}
// If you wanted an int array
// int[] array = new int[list.size()];
// for( int i = 0; i < array.length; i++){
// array = list.get(i);
// }
return list;
}

Cheers,

Dan Andrews
- - - - - - - - - - - - - - - - - - - - - - - - -
Ansir Development Limited http://www.ansir.ca
- - - - - - - - - - - - - - - - - - - - - - - - -
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top