You are on page 1of 3

Experiment No- 9

// Name
Roll No.-159
//Div:B

Title: Implementation of Collection (ArrayList,LinkedList).


Problem Statement:
Write a program to read a text file one line at a time. Read each line as a String
and place
that String object into a LinkedList. Print all of the lines in the LinkedList in
reverse order.

Program:
import java.util.*;
import java.io.*;
class Expt10{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
try{
System.out.println("Enter the name of the file :");
String fname=sc.next();
System.out.println("File Exist");

//ArrayList<String> c=new ArrayList<String>();


LinkedList<String> c=new LinkedList<String>();
BufferedReader br=new BufferedReader(new FileReader(fname));//read
existing file
String line;
while((line=br.readLine())!=null)
{
System.out.println(line);
c.add(line); //add elements of file into
collection
}
System.out.println("Collection is :"+c);

/*Iterator itr=c.iterator();
while(itr.hasNext())
{
System.out.println(itr.next());
}*/

for(String s:c)
{
System.out.println(s);
}
System.out.println("*************************");
System.out.println("Reverse order is :");
Collections.reverse(c);
Iterator itr1=c.iterator();
while(itr1.hasNext())
{
System.out.println(itr1.next());
}
}catch(Exception e)
{
System.out.println(e);
}
}
}

OUTPUT:

You might also like