为什么程序在 out.txt 中没有显示答案?

Why program did not show answer in out.txt?

代码应该做一个反转并将结果输出到out.txt,但是这并没有发生,你能解释一下我在代码中的错误吗?提前致谢

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

您正在尝试反转字符串两次,因为字符串正在恢复为原始字符串。此外,for 循环内有一个不必要的(根据我的理解)while 循环(我已在我的回答中删除了它)。

试试下面的代码:

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

阅读文件编写器 here 如何 flush 数据并在写入完成后关闭 writer