Welcome to HBH! If you have tried to register and didn't get a verification email, please using the following link to resend the verification email.

Reading text file line by line in JAVA


ghost's Avatar
0 0

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.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