Tech Support Guy banner
Status
Not open for further replies.
1 - 4 of 4 Posts

·
Registered
Joined
·
272 Posts
Discussion Starter · #1 ·
Hey all,

Take for example the following text file...

a
aa
aaabaaa
madamiamadam

...

I have this code here to read the file,

Code:
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
 

·
Registered
Joined
·
6,649 Posts
Hi r3drock3t88,

The best way to read a file line by line is to use an instance of the BufferedReader class.
Example :
Code:
[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]
 
1 - 4 of 4 Posts
Status
Not open for further replies.
Top