# Reversing the lines of file

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.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);
FileInputStream inputFile = null;
StringBuilder textInput= new StringBuilder();
String line=null;
try {

inputFile = new FileInputStream(file);

//read the file line by line and append the separator
textInput.append(line+SEPERATOR);
}
inputFile.close();

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.

• 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. Feb 20 '15 at 13:07
• 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? Feb 20 '15 at 13:10
• See also this other similar question. Feb 20 '15 at 14:09

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 {
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();
}

}

• Will this work in a Java 7 enviornment? "Files" requires "nio" package. Is it advisable to use it during an Interview? Feb 20 '15 at 13:30
• 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. Feb 20 '15 at 13:31
• ok. Is the "Files" faster than BufferedReader when reading large files? Feb 20 '15 at 13:57
• 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 Feb 20 '15 at 14:21