1

I need to import a text file and export a text file with the lines in the opposite order

Example input:

abc

123

First line

Expected output:

First line 

123

abc

This is what I have so far. It reverses the lines but not the line order. Any help would be appreciated

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;

public class reversetext {

    public static void main(String[] args) throws IOException {
        try {

            File sourceFile = new File("in.txt");//input File Path
            File outFile = new File("out.txt");//out put file path

            Scanner content = new Scanner(sourceFile);
            PrintWriter pwriter = new PrintWriter(outFile);

            while(content.hasNextLine()) {
                String s = content.nextLine();
                StringBuffer buffer = new StringBuffer(s);
                buffer = buffer.reverse();
                String rs = buffer.toString();
                pwriter.println(rs);
            }
            content.close();    
            pwriter.close();
        }
        catch(Exception e) {
              System.out.println("Something went wrong");
        }
    }
}
baitmbarek
  • 2,440
  • 4
  • 18
  • 26
NarrowSky
  • 49
  • 5
  • So you want the last line to be the first? So you can either append new lines to the beginning of the out.txt OR you store all lines and write them after reading by iterating over them, starting with size()-1. – maio290 Jan 19 '20 at 19:34

1 Answers1

1

Easiest possible answer I can come up, using Java 7+ and not relying on deprecated building blocks like Stack is the following:

private static final String INPUT_FILE = "input.txt";
private static final String OUTPUT_FILE = "output.txt";
private static final String USER_HOME = System.getProperty("user.home");

public static void main(String... args) {
    try {
        try (PrintWriter writer = new PrintWriter(Files.newBufferedWriter(Paths.get(USER_HOME + "/" + OUTPUT_FILE)))) {
            Files
             .lines(Paths.get(USER_HOME + "/" + INPUT_FILE))
             .collect(Collectors.toCollection(LinkedList::new))
             .descendingIterator()
             .forEachRemaining(writer::println);
        }
    } catch (Exception e) {
        e.printStackTrace();
        System.exit(1);
    }

}

Just read in the input file and acquire a stream of it's contents in String (Files#lines). Then collect those into a LinkedList using the descending iterator, loop over them and write them out to the output file.

akortex
  • 5,067
  • 2
  • 25
  • 57
  • You can also use a `Deque` instead of a `Stack`, with `ArrayDeque` being a very efficient implementation. – Zabuzard Jan 19 '20 at 22:07