我正在尝试将控制台输出导出到文本文件。此输出也来自串行端口。但是,我做不到,它只打印一行。谁能帮我? 我编写的代码如下。
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("");
它只打印一行
因为你使用System.out.print(array[i] + " ");
,
您可以将其更改为System.out.println(array[i] + " ");
您需要一个流来同时写入控制台和文件,您可以使用commons-io的一部分来创建此流TeeOutputStream
该流,将流作为参数提供给控制台,流到文件
PrintStream original = System.out; //the stream of the console
FileOutputStream fileOut = new
FileOutputStream("C:\Users\khas\Desktop\output.txt"); //the stream of your file
OutputStream outputtee = new TeeOutputStream(originalOut, fileOut); //join both streams
PrintStream printTee = new PrintStream(outputTee);
System.setOut(printTee); // and set as the default out