SE251Ex:File Reverser
Reversing lines from a file
Description
Write a simple program that asks the user for a file name, reads in the specified file line by line and prints them out in reverse order. Below is an example output (user input indicated by text enclosed in '<' and '>') of running the program.
Enter file name: <test.txt> Reversed file contents: ----------------------- yours? What's Yul. Hong is name my Hello,
As you can guess, the original contents of the file <test.txt> is:
Hello, my name is Hong Yul. What's yours?
Below is a skeleton class to get you started:
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; public class FileReverser { public FileReverser() { System.out.print("Enter file name: "); //Your code here } public static void main(String[] args) { new FileReverser(); } }
Tips
- In short, reading user input from the console can be achieved through this:
BufferedReader console = new BufferedReader(new InputStreamReader(System.in)); String input = console.readLine(); //throws IOException
Both BufferedReader and InputStreamReader are subclasses of Reader, which provides mechanisms for reading from character streams - be they from a file, the console or through a network. What we are doing here is first creating a new InputStreamReader that reads from System.in (i.e. the console), then we are "wrapping" it up in a BufferedReader, which provides a more efficient and flexible way of reading character streams. The method readLine() is a convenient method for reading a block of characters in a single line. Each time a readLine() is called on a BufferedReader, it reads the next sequence of characters until a newline is reached, and returns the result as a String object.
- Similarly, reading from a file can be done through:
BufferedReader file = new BufferedReader(new FileReader("C:/yourfilenamehere.txt")); //throws IOException String line1 = file.readLine(); //throws IOException String line2 = file.readLine(); //etc...
Now instead of an InputStreamReader we use a FileReader, which indeed is specifically designed to read character streams from a file, specified by giving its filename as a String or a File object. We again wrap it up around a BufferedReader because it allows us to read the file line by line. When we reach the end of the file, the readLine() method returns null. Thus we can use this as a loop termination condition in order to be able to read an arbitrary number of lines from a file.
Discussion
Here you can ask questions and discuss stuff