adrianjohnson
Programmer
I'm fairly new to Java, and looked on the net, but the read from file code I've seen do nothing with the input. What I'd like to do is read a line from a text file, pop it in an array, and then process it later on.
The code I've done is:
String record = null;
int recCount = 0;
int noRec = 0;
// Get the number of lines to process, so the array can be built.
// Is there a better way of doing this?
try
{
FileReader fr = new FileReader("rem.txt");
BufferedReader br = new BufferedReader(fr);
record = new String();
while ((record = br.readLine()) != null)
{
recCount++;
}
}
catch (IOException e)
{
// catch possible io errors from readLine()
System.out.println("Error reading from the file!");
e.printStackTrace();
}
// Create array based on number of lines in text file.
noRec = recCount;
String[] remLine = new String[noRec];
// Read each line, and add to array.
try
{
FileReader fr2 = new FileReader("rem.txt");
BufferedReader br2 = new BufferedReader(fr2);
recCount = 0;
noRec = 0;
while ((remLine[noRec] = br2.readLine()) != null)
{
System.out.println(recCount + ": " + remLine[noRec]);
recCount++;
}
}
catch (IOException e)
{
// catch possible io errors from readLine()
System.out.println("Error reading from the file!");
e.printStackTrace();
}
// This line not working properly, as it returns null.
System.out.println(remLine[noRec]);
// How do I process what's in remLine here????
Thanks,
Adrian Johnson
Adrian Johnson
Assystance - i.t. solutions
The code I've done is:
String record = null;
int recCount = 0;
int noRec = 0;
// Get the number of lines to process, so the array can be built.
// Is there a better way of doing this?
try
{
FileReader fr = new FileReader("rem.txt");
BufferedReader br = new BufferedReader(fr);
record = new String();
while ((record = br.readLine()) != null)
{
recCount++;
}
}
catch (IOException e)
{
// catch possible io errors from readLine()
System.out.println("Error reading from the file!");
e.printStackTrace();
}
// Create array based on number of lines in text file.
noRec = recCount;
String[] remLine = new String[noRec];
// Read each line, and add to array.
try
{
FileReader fr2 = new FileReader("rem.txt");
BufferedReader br2 = new BufferedReader(fr2);
recCount = 0;
noRec = 0;
while ((remLine[noRec] = br2.readLine()) != null)
{
System.out.println(recCount + ": " + remLine[noRec]);
recCount++;
}
}
catch (IOException e)
{
// catch possible io errors from readLine()
System.out.println("Error reading from the file!");
e.printStackTrace();
}
// This line not working properly, as it returns null.
System.out.println(remLine[noRec]);
// How do I process what's in remLine here????
Thanks,
Adrian Johnson
Adrian Johnson
Assystance - i.t. solutions