reading lines from text file (java)

Vote Down
Score
2
Vote Up
February 28, 2005 at 00:20:00 Pacific
Specs: win xp, p2

What would be the best way to read lines from a text file in java?
The user gives me a text file which is already in a given format (i know how many lines the file has and which lines are Strings or integers).

example of a text file would be:

1
2
green
blue

i want to take the first line and say if its 1, move onto this method and if its 2 move onto this method, then both of those methods (whichever is called tho) will look at the second line and do the same. Then the last two lines are taken as Strings and = some data members say favoriteColor1 and favoriteColor2 and then from there i can use those data members in the rest of the program. thanks.


Reply ↓  Report •


#1
Vote Down
Score
17
Vote Up
February 28, 2005 at 10:21:47 Pacific

There's a few ways you can do this (maybe something new in Java 1.5), but to read a general file in I usually like to read line by line and store it in an ArrayList.

This example I have should help:

=====================================================================

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

public class FileIO
{
    public static void main(String[] args)
    {
        ArrayList bob = loadFile(args[0]);
        for (int i=0; i<bob.size(); i++)
            System.out.println(i+1 + ":\t" + bob.get(i));
    }

    public static ArrayList loadFile(String fileName)
    {
        if ((fileName == null) || (fileName == ""))
            throw new IllegalArgumentException();
        
        String line;
        ArrayList file = new ArrayList();

        try
        {    
            BufferedReader in = new BufferedReader(new FileReader(fileName));

            if (!in.ready())
                throw new IOException();

            while ((line = in.readLine()) != null)
                file.add(line);

            in.close();
        }
        catch (IOException e)
        {
            System.out.println(e);
            return null;
        }

        return file;
    }
}



Reply ↓  Report •
Reply to Message Icon Start New Discussion
Related Posts

« c++ help executing command shortcu... »

This post is quite old and has been locked from receiving new replies. Please create a new posting instead.

Ask the Community!
Describe your Problem
Example: Hard Drive Not Detected on My PC