Link to home
Start Free TrialLog in
Avatar of tristatefab
tristatefab

asked on

Opening Text File, Read Each Line in it and Output With Line Number Before Each Line

Hello Experts,

I have a file that I cannot get to work properly after several attempts... I am trying to read every line from a text file called inventory.txt  which contains:

bear, 6 94962 11263 4
ball, 4 89012 48129 3
train, 6 94551 11003 3
doll, 6 94551 11263 4
train, 6 94551 11003 3
car, 4 32551 48003 3
ball, 4 89012 48129 3
doll, 6 94551 11263 4

then output each line to the screen with a line number before them... Here is my code so far that does not work properly, I am sure there is a more efficient way of getting it to work...

import java.io.*;
import java.util.*;

public class ReadTextFile
{
    public static void main(String[] args)
    {
        ReadTextFile inventory = new ReadTextFile();
        ArrayList newFile = inventory.ReadFile("inventory.txt");
        int fsize = 0;
        int ln = 0;
        while (fsize < newFile.size())
       {
                ln = fsize + 1;
                System.out.println("line: " + ln + "\t" + newFile.get(fsize));
                fsize++;
        }
    }

    public ArrayList ReadFile(String fileName)
    {

        String thisLine;
        ArrayList file = new ArrayList();
        try
        {
            BufferedReader buffer = new BufferedReader(new FileReader(fileName));

            thisLine = buffer.readLine();
            while (thisLine != null)
            {
                  
                  file.add(thisLine);
                  thisLine = buffer.readLine();
            }
            buffer.close();
        }
            
      catch (IOException e)
            {
                  
            }
      return file;
    }
}











Avatar of David_Ryan
David_Ryan

Assuming that inventory.txt is in the C:\Temp\ directory, this line:
ArrayList newFile = inventory.ReadFile("inventory.txt");

Should be like this:

ArrayList newFile = inventory.ReadFile("C:" + File.separator + "Temp" + File.separator + "inventory.txt");

With that change, the program works fine for me.

Avatar of tristatefab

ASKER

How could I modify the program to pass the file name as an argument?
How could I modify the program to pass the file name as an argument? I need to use FileReader and BufferedReader to open and read it somehow.
ASKER CERTIFIED SOLUTION
Avatar of Mick Barry
Mick Barry
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial