I'm very new to Java programming, and this is actually part of a problem I need to solve for homework: I am reading the contents of a file line by line as a String into an ArrayList for later processing. I need the program to print out to console the contents of the ArrayList on separate lines, but the output after I run the compiled file prints the first line of the file, then prints the first and second lines together on the next line, then prints the first, second and third lines of the program.
My understanding of how this is supposed to work is that the program will take my file, the FileReader and BufferedReader will grab the lines of text in the file as Strings, which are then placed in the ArrayList with each String at a different position in the ArrayList right? Can someone please tell me where in the while loop I'm going wrong? Thanks!
Code:
public class ArrayListDemo
{
public static void main (String[]args)
{
try
{
ArrayList<String> demo= new ArrayList <String>();
FileReader fr= new FileReader("hi.tpl");
BufferedReader reader= new BufferedReader(fr);
String line;
while ((line=reader.readLine()) !=null)
{
//Add to ArrayList
demo.add(line);
System.out.println(demo);
}
reader.close();
}catch (Exception e)
{
System.out.println("Error: "+e.getMessage());
System.exit(0);
}
}
}
Obtained output:
cat
cat, rat
cat, rat, hat
Expected output:
cat
rat
hat
The output you are seeing each time is the result of ArrayList.toString() being printed to standard out. Instead, loop through the ArrayList after you've finished reading the contents of the file into the ArrayList:
while ((line=reader.readLine()) !=null) {
//Add to ArrayList
demo.add(line);
}
reader.close();
//do fun stuff with the demo ArrayList here
for (String s : demo) { System.out.println(s); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With