In: Computer Science
Write a program that will write the contents of a text file backwards one character at a time. Your program should first ask for the text file name to be processed – and after verifying that the file exists, it should read the file into a StringBuilder buffer. Save the new file using the old filename appended with “Ver2-“ at the front. So for the file “MyStuff.txt” the file would be saved as Ver2-MyStuff.txt”. You can use any text file to test your work.
MainProgram.java
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class MainProgram {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.print("Enter the file: ");
String filename = console.next();
File file = new File(filename);
// checking if file exists or not
if(!file.exists()){
System.out.println("File not exists...");
return;
}
StringBuffer buffer = new StringBuffer();
try {
// reading file and storing into buffer
Scanner fileReader = new Scanner(new File(filename));
while (fileReader.hasNextLine()){
buffer.append(fileReader.nextLine()+"\n");
}
}catch (IOException e){
System.out.println(e.getMessage());
return;
}
String outFile = "Ver2-"+filename;
try {
// writing to file in backwards
FileWriter writer = new FileWriter(new File(outFile));
for(int i=buffer.length()-2; i>0; i-- )
writer.write(buffer.charAt(i));
writer.write("\n");
writer.flush();
writer.close();
System.out.println("Output written to "+outFile);
}
catch (IOException e){
System.out.println(e.getMessage());
}
}
}
// OUT
>javac MainProgram.java
>java MainProgram
Enter the file: words.txt
Output written to Ver2-words.txt