Create a class that allows the user to select a file and output the contents of the file to the console. Recommend using a text file to display, java files are text files. You may want to put this code in a method to allow you to complete the remainder of this assignment without overwriting your code.
a. You should ask the user to enter the full path to your file to make certain you are processing the correct file.
2. Modify your code/add a method to display the contents of the file in reverse order. You do not need to reverse the characters on each line but simply output the lines of the file in reverse order.
a. Hint: read the content of the file into an ArrayList and then traverse the ArrayList.
this is what i go so far.
package classActivity;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
public class Select
{
public static String enterFilePath()
{
Scanner input = new Scanner(System.in);
System.out.println("Enter path file ");
String path = input.nextLine();
return path;
}
public static ArrayList<String> readInFile(String path)
{
ArrayList<String> lines = new ArrayList<String>();
File fr = null;
Scanner inputFile = null;
try
{
fr = new File(path);
inputFile = new Scanner(fr);
while (inputFile.hasNextLine())
{
lines.add(inputFile.nextLine());
}
}
catch (FileNotFoundException fnf)
{
System.out.println(fnf.getMessage());
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
finally
{
if (inputFile != null)
{
inputFile.close();
}
}
return lines;
}
//seperate method Collections.reverse(al);
public static void Reverse(ArrayList<String> lines)
{
Collections.reverse(lines);
}
public static void Save(ArrayList<String> lines)
{
File file = null;
PrintWriter out = null;
try
{
file = new File(enterFilePath());
out = new PrintWriter(file);
for (String element: lines)
{
out.println(lines);
}
}
catch (Exception e)
{
}
finally
{
if (out != null)
{
out.close();
}
}
}
public static void main(String[] args)
{
String fileName = enterFilePath();
ArrayList<String> lines = readInFile(fileName);
Reverse(lines);
Save(lines);
}
}