# Solved: Reading text file line by line in JAVA - Help PLZ



## r3drock3t88 (Jan 13, 2007)

Hey all,

Take for example the following text file...

a
aa
aaabaaa
madamiamadam

...

I have this code here to read the file,


```
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.FileInputStream;
public class FileCode
    {

    public static void main(String[] args) throws IOException
        {
        
        int next;
        char c;
        char[] message = new char[10000];
        String str;
        int count = 0;
        Stack stack = new Stack();
        
        
        String fileName = "c:\\prog4DS.dat";
        FileReader reader = new FileReader(fileName);
        FileWriter writer = new FileWriter("FileStuff.dat");
        
        next = reader.read();
        
        while(next != -1)
            {
                c = (char) next;
                message[count] = c;
                next = reader.read();
                count++;
            }
        
        reader.close();
        
        for(int i = 0; i < count; i++)
        {
            System.out.print(message[i]);
            writer.write(message[i]); 
        }

        writer.close();

        }

    }
```
Basically what I want is to read each line of the text file individually and store the text in its own location of an array. So for example, for the first line in the text file it is simply just an "a". I would like the program to recognize that "a", and assign it to the array.

Could anyone please assist me on how I'd go about doing this? Thank you all very much! It's much appreciated


----------



## Chicon (Jul 29, 2004)

Hi r3drock3t88,

The best way to read a file line by line is to use an instance of the *BufferedReader* class.
Example :

```
[SIZE=2]
   List<String> list = new ArrayList<String>();
   String line;
   ...
   ...
   String fileName = "c:\\prog4DS.dat";
   FileReader reader = new FileReader(fileName);
   BufferedReader bufrdr = new BufferedReader(reader);
   line = bufrdr.readLine();
   while (line != null) {
      list.add(line);
      line = bufrdr.readLine();
   }
   bufrdr.close();
   reader.close();
   ...
   ...
   String[] array = new String[list.size()];
   list.toArray(array);
[/SIZE]
```


----------



## r3drock3t88 (Jan 13, 2007)

Thank you Chicon,

I used the bufferreader and managed to get my project finished . Thanks again!


----------



## Chicon (Jul 29, 2004)

:up: You're welcome !


----------

