The code should do a reverse and output the result to out.txt, but this does not happen, can you explain my mistake in the code. Thanks in advance
import java.io.BufferedReader; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; public class Main { public static void main(String[] args) throws IOException { FileReader input = new FileReader("in.txt"); FileWriter output = new FileWriter("out.txt"); BufferedReader sb = new BufferedReader(input); String data; while ((data = sb.readLine()) != null) { String[] words = data.split(" "); for (String a : words) { StringBuilder builder = new StringBuilder(a); builder.reverse(); while ((sb.read()) != -1) { output.write(String.valueOf(builder.reverse())); } } } } }
Advertisement
Answer
You are trying to reverse the string twice because of that the string is getting back to the original string. Also, there is an unnecessary (as per my understanding) while
loop inside the for
loop (I have removed that in my answer).
Try the below code:
import java.io.BufferedReader; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; public class Main { public static void main(String[] args) throws IOException { FileReader input = new FileReader("in.txt"); FileWriter output = new FileWriter("out.txt"); BufferedReader sb = new BufferedReader(input); String data; while ((data = sb.readLine()) != null) { String[] words = data.split(" "); // above statement can be replaced with // String[] words = data.split(" {34}"); for (String a : words) { StringBuilder builder = new StringBuilder(a); // why while loop is required? //while ((sb.read()) != -1) { output.write(builder.reverse().toString()); output.flush(); // flush data to the file //} } } output.close(); } }
Read about File writer here on how to flush
data and also close the writer
after writing is completed.