Arrange lines of a text file This program orders the lines of a text file alphabetically and prints them out to a new text file.

Usage:

java Arranger input.txt output.txt


Is this the best and especially the most performant way?

import java.io.File;
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.FileWriter;
import java.io.BufferedWriter;
import java.io.IOException;
import java.util.ArrayList;

/*
 * this program arranges the lines of a text file in it's alphabetical order
 * usage: java Arranger input.txt output.txt
 */

public class Arranger { 

    public static void main(String[] args) {

        File inputFile = new File(args[0]);
        File outputFile = new File(args[1]);
        ArrayList&lt;String&gt; words = new ArrayList&lt;&gt;();

        try (BufferedReader reader = new BufferedReader(new FileReader(inputFile))) {
            // read lines of file and order them
            String line = new String();
            while ((line = reader.readLine()) != null) {
                words.add(line);
            }
            words.sort(String::compareToIgnoreCase);
        } catch (IOException e) {
            e.printStackTrace();
        }

        // write ordered list of words to file
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(outputFile))) {
            for (String word : words) {
                writer.write(word + "\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
You can probably do something like this as well:

Files.lines(path)


It gets all the lines from the file as a stream, then you can sort the string based on your logic and then collect the same in a list and write to the output file.

This answer gives you a functional programming approach. Most part of the method is self-explanatory.

Files.write(
            Paths.get(outFile), 
            Files.lines(Paths.get(path))
                .sorted(String::compareToIgnoreCase)
                .collect(Collectors.toList())
    );