Tom's Guide | Tom's Hardware | Tom's Games
![]() |
![]() |
![]() |
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
bluei 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.

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;
}
}

![]() |
Letting Ghost search for ...
|
executing command shortcu...
|

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