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.