3
\$\begingroup\$

I have written a program to reverse the lines of a file. I made use of the String [] approach with the String.split(separator) using a custom separator.

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;


public class ReverseTheLinesOfaFile {


private static final String  SEPERATOR="-";

/**
 * This function reads the data of the file and then reverses the lines of the file keeping
 * the content as the same
 * @param fileName
 */
private void reverseLines(String fileName) {
    // TODO Auto-generated method stub
    File file = new File(fileName);
    //get the readers ready
    FileInputStream inputFile = null;
    StringBuilder textInput= new StringBuilder();
    String line=null;
    try {

        inputFile = new FileInputStream(file);
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputFile));

        //read the file line by line and append the separator
        while ((line= reader.readLine())!=null){
            textInput.append(line+SEPERATOR);
        }
        reader.close();
        inputFile.close();

        //get the writers ready
        FileOutputStream outputFile = new FileOutputStream(file);
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputFile));

        String[] lines   = textInput.toString().split(SEPERATOR);

        //write line by line to the file
        for (int i= lines.length-1 ; i > -1 ; --i){
            writer.write(lines[i]+"\n");
        }
        writer.flush();
        writer.close();
        System.out.println("file reversing done");
    } catch (FileNotFoundException e) {
        System.out.println("The file with name ="+file.getName()+" could not be found");
        e.printStackTrace();
    } catch (IOException e) {
        System.out.println("There has been a IO exception");
        e.printStackTrace();
    }
}

public static void main(String[] args) {

    ReverseTheLinesOfaFile linesOfaFile = new ReverseTheLinesOfaFile();
    linesOfaFile.reverseLines("data.txt");
}

}

I want to know whether this can be done even more efficiently and without the use of the Seprator variable. The file can contain all sorts of characters in the ASCII table.

\$\endgroup\$
3
  • \$\begingroup\$ why don't you update the list of string while reading from file? Then you don't need to use separator. Also since your file may contain any character, using '-' as separator may lead to incorrect output. \$\endgroup\$ Feb 20, 2015 at 13:07
  • \$\begingroup\$ That is exactly what I need help with. Can you demonstrate your solution. Are you suggesting to use List<String> and then use a descending iterator to get the reverse of the file? \$\endgroup\$
    – Aneesh K
    Feb 20, 2015 at 13:10
  • \$\begingroup\$ See also this other similar question. \$\endgroup\$
    – janos
    Feb 20, 2015 at 14:09

1 Answer 1

5
\$\begingroup\$

You have a number of open resoruces that you do not close properly, FileOutputStreams, BufferedWriters, etc. These should be handled with a try-with-resources block.

Additionally, the standard Java libraries contain helper methods that will make this operation almost trivial... See Files.readAllLines()

Together, this could all be done as:

private static void reverseLines(String fileName) {
    Path path = Paths.get(fileName);
    try {
        List<String> lines = Files.readAllLines(path);
        try (BufferedWriter writer = Files.newBufferedWriter(path)) {
            ListIterator<String> lineIterator = lines.listIterator(lines.size());
            while (lineIterator.hasPrevious()) {
                writer.write(lineIterator.previous());
                writer.newLine();
            }
        }
    } catch (IOException ioe) {
        ioe.printStackTrace();
    }

}
\$\endgroup\$
4
  • \$\begingroup\$ Will this work in a Java 7 enviornment? "Files" requires "nio" package. Is it advisable to use it during an Interview? \$\endgroup\$
    – Aneesh K
    Feb 20, 2015 at 13:30
  • 3
    \$\begingroup\$ Yes, this is all standard in Java 7. Files was introduced as a major feature in Java7 (along with the try-with-resources). Using it in an interview would absolutely be the better option than reinventing stuff. \$\endgroup\$
    – rolfl
    Feb 20, 2015 at 13:31
  • \$\begingroup\$ ok. Is the "Files" faster than BufferedReader when reading large files? \$\endgroup\$
    – Aneesh K
    Feb 20, 2015 at 13:57
  • 1
    \$\begingroup\$ Most likely yes, but by the time the differences start to add up you will be running in to other limits like memory space, Disk IO, and other things, not the java side of the problem \$\endgroup\$
    – rolfl
    Feb 20, 2015 at 14:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.