Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Read array of integers from file

Say i have a file called "input.txt" that has a bunch of positive integers in it:

6
5
6
8
6
2
4

and so on....(one integer per line)

I want to read this file and make it into an array. The first integer (in this case 6) tells the number of indexes or elements in the array, so 6 spots. The other numbers fill in the array starting at 0. So at index 0, the number is 5, at index 1 the number is 6, and so on.

Can someone please show me how to read this file and make it into an array called A and return the integers in each index as n?

this is what i have so far:

import java.io.*;
public class inputFile {
    public static jobScheduleRecursive(int[] A, int i)
    {
        try
    {
        FileReader filereader = new FileReader("input.txt");
        BufferedReader bufferedreader = new BufferedReader(filereader);
        String line = bufferedreader.readLine();
        //While we have read in a valid line
        while (line != null) {
            //Try to parse integer from the String line
            try {
                System.out.println(Integer.parseInt(line));
            } catch (NumberFormatException nfe) {
                System.err.println("Failed to parse integer from line:" + line);
                System.err.println(nfe.getMessage());
                System.exit(1);
            }
            line = bufferedreader.readLine();
        }
    }
    catch(FileNotFoundException filenotfoundexception)
    {
        System.out.println("File not found.");
    }
    catch(IOException ioexception)
    {
        System.out.println("File input error occured!");
        ioexception.printStackTrace();
    }
    return A;
}

I think i'm doing something completely wrong. please help.

like image 623
user986024 Avatar asked Oct 09 '11 18:10

user986024


2 Answers

Using a Scanner and the Scanner.nextInt() method, you can solve this in just a few lines:

Scanner s = new Scanner(new File("input.txt"));
int[] array = new int[s.nextInt()];
for (int i = 0; i < array.length; i++)
    array[i] = s.nextInt();
like image 111
aioobe Avatar answered Oct 07 '22 00:10

aioobe


Java 8+

int[] ints = Files.lines(Paths.get("input.txt"))
                  .mapToInt(Integer::parseInt).toArray();
like image 21
Andrew Avatar answered Oct 07 '22 01:10

Andrew