Nikki
Nikki

Reputation: 13

How to print a file's contents backwards?

I have an assignment where I need to read a file's contents in reverse, like this:

Original:

This is how you reverse a file, 10

New:

10 ,file a reverse you how is This

Here's the code I have:

public static void main(String [args]{
    Path file = Paths.get("C:\\Java\\Sample.txt");
    InputStream input = null;
    ArrayList<String> words = new ArrayList<String>();
    try{
    input = Files.newInputStream(files);
    BufferedReader reader = new BufferedReader(new InputStreamReader(input));
    String s;
    while((s = reader.readLine()) != null)
        words.add(s);
    for(int i = words.size() - 1; i >= 0; i--){
            System.out.print(words.get(i));
    }
    catch(Exception e){
        System.out.println(e);
    }
}

Sorry if the formatting is off. The program simply reads the file in original form. What am I doing wrong? Can anyone explain what I need to have this print backwards? My textbook doesn't explain anything. Also, I realize that my catch block is possibly too broad. I'll work on that.

EDIT: I forgot to add the ArrayList code when typing this out. It exists already in my original program.

Thank you

Upvotes: 0

Views: 130

Answers (1)

John Kugelman
John Kugelman

Reputation: 361849

while((s = reader.readLine()) != null)
    words.add(s);

The second line implies that s holds words, but the first line reads a line at a time. You need to read a word at a time, or split the lines into words.

Upvotes: 2

Related Questions