java - 将控制台输出写入 .txt 文件

标签 java bufferedreader bufferedwriter

我正在尝试将 java 控制台输出写入桌面上的 .txt 文件。 但是当该方法启动时,我有控制台输出并创建了 txt 文件,但它是空的,我意识到 BufferedReader (in) 不起作用...(因为“ok1 - i”语句)

问题是为什么?或者我的代码有什么问题? 这是我的代码,因此您可以查看并运行它

   package noobxd;

   import java.io.BufferedReader;
   import java.io.BufferedWriter;
   import java.io.FileWriter;
   import java.io.IOException;
   import java.io.InputStreamReader;
   import java.util.Random;

   public class Main {

public static void main(String[] args) throws IOException {
    String path = "C:\\Users\\Mario\\Desktop\\output.txt";

    generate_codes();

    writetxt(path);
}

private static void writetxt(String path) throws IOException {
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

    BufferedWriter out = new BufferedWriter(new FileWriter(path));
    try {
        String inputLine;
        inputLine = "";
        int i=0;
        System.out.println("Starting");
        while (!inputLine.isEmpty()){
            System.out.println("ok1"+i);
            inputLine = in.readLine();
            System.out.println("ok2"+i);
            out.write(inputLine);
            System.out.println("ok3"+i);
            out.newLine();
            System.out.println("ok4"+i);
            i++;
        }
        System.out.print("Write Successful");
    } catch (IOException e1) {
        System.out.println("Error during reading/writing");
    } finally {
        out.close();
        in.close();
    }
}

private static void generate_codes() {
    Random rnd = new Random();
    for (int i = 0; i < 30; i++) {
        int code = rnd.nextInt(201) + 100;
        int students = rnd.nextInt(31) + 40;
        int j = rnd.nextInt(4);
        String type = new String();
        switch (j) {
            case 0:
                type = "Theory";
                break;
            case 1:
                type = "Lab";
                break;
            case 2:
                type = "Practice";
                break;
            case 3:
                type = "Exam";
                break;
        }
        System.out.println("TEL" + code + "-TopicNumber" + i + "-" + students + "-" + type);

    }
}
}

感谢您的宝贵时间,请帮我解决我的问题。

最佳答案

String inputLine;
inputLine = "";
...
while (!inputLine.isEmpty())  // this is false and so the loop is not executed

以后,请学会使用调试工具,更仔细地阅读你的代码。如果您想读取直到 EOF,请使用

while ((inputLine = in.readLine()) != null) {
    ...
}

关于java - 将控制台输出写入 .txt 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17533694/

相关文章:

java - 安卓资源管理

java - BufferedWriter 未将文本写入文本文件

java - java读取文件错误

java - BufferedWriter 和 Calendar.getTime() 的问题 : If BufferedWriter has to wait, Calendar 对象卡住

java - 输出文件新行不从下一行开始

java - 如果我的类实现了 Serializable,我是否必须在其子类中实现它?

java - Eclipse 运行配置 - 单个配置中的多个运行配置?

java - BufferedReader 在应该的时候没有说明 'ready'

java - 线程中的异常 "AWT-EventQueue-0"java.lang.StringIndexOutOfBoundsException : String index out of range: 8

java - 从文件中执行 db 语句