如何在 Java 中将控制台数据转换为文本文件

我正在尝试将控制台输出导出到文本文件。此输出也来自串行端口。但是,我做不到,它只打印一行。谁能帮我?我写的代码如下。


 String input = new String(buffer, 0, len); // convert buffer to string

        myLinkedList = removeComma(input); //format string data 

        String[] array = myLinkedList.toArray(new String[myLinkedList.size()]); // put array the formatted data



        PrintStream fileOut = new PrintStream(new FileOutputStream("C:\\Users\\khas\\Desktop\\output.txt"));

        System.setOut(fileOut);

        for (int i = 0; i < array.length; i++) {

            System.out.print(array[i] + " ");


        }

        System.out.println("");


明月笑刀无情
浏览 267回答 2
2回答

PIPIONE

它只打印一行因为你使用System.out.print(array[i] + " ");,你可以把它改成&nbsp;System.out.println(array[i] + " ");

茅侃侃

您需要一个流同时写入控制台和文件,您可以通过使用commons-io 的TeeOutputStream一部分将流到控制台和流到文件作为参数来创建此流PrintStream original = System.out; //the stream of the consoleFileOutputStream fileOut = new&nbsp;FileOutputStream("C:\\Users\\khas\\Desktop\\output.txt"); //the stream of your fileOutputStream outputtee = new TeeOutputStream(originalOut, fileOut); //join both streamsPrintStream printTee = new PrintStream(outputTee);System.setOut(printTee); // and set as the default out
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java