Zhi J Teoh
Zhi J Teoh

Reputation: 61

How do I read lines from a file and store them into an array

So basically what I'm trying to do is read this file called Products.csv, and then I want to store each lines of it (445 lines) into an array of length 445.

For some reason, if I typed System.out.println (lines[2]); for example, it does read out the line 2 of the file, however, if I used a loop to read out all the lines with this code System.out.println (lines[a]) while in a loop, it shows me all null null null....

public class Lab2 
{
        String [] lines = new String [446];
        int x = 0;
    File inFile;

    public long ReadFile(String sfile) throws IOException 
    {
        inFile  = new File(sfile);
        BufferedReader reader = new BufferedReader(new FileReader(inFile));
        String sline = null;
        while ((sline=reader.readLine()) != null) 
        {
                lines[x]=sline;
                x++;
        }
        reader.close();  
        return inFile.length();
         }

        public void OutputLines (String [] s)
        {
            for (int a=0;a<s.length;a++)
            {
               System.out.println (s[a]); 
            }
        }

    public static void main(String[] args)
    {
        try
        {
            Lab2 read = new Lab2();
            read.ReadFile("Products.csv");

        }
        catch (IOException e)
        {
            System.out.println(e.getMessage());
        }

                Lab2 reader = new Lab2 ();
                reader.OutputLines(reader.lines);
        }
}

Upvotes: 2

Views: 74

Answers (1)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285403

You're reading the lines into one Lab2 object, then creating a totally new different Lab2 object to display the results. Don't do that since the 2nd Lab2 object has not been filled with data and thus its array is filled with nulls. Instead use the same Lab2 object for both reading and displaying.

Change

public static void main(String[] args)
{
    try
    {
        Lab2 read = new Lab2();
        read.ReadFile("Products.csv");

    }
    catch (IOException e)
    {
        System.out.println(e.getMessage());
    }

            Lab2 reader = new Lab2 ();
            reader.OutputLines(reader.lines);
    }

to

public static void main(String[] args) {
    try {
        Lab2 read = new Lab2();
        read.ReadFile("Products.csv");

        // *** display data from the same Lab2 object ***
        read.OutputLines(); // this shouldn't take a parameter
    } catch (IOException e) {
        e.printStacktrace();
    }

Upvotes: 3

Related Questions