1

I'm trying to export my console output to the text file. This output also comes from the serial port. But, I couldn't do it, it prints only one line. Can anyone help me? The code that I wrote is below.

 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("");
vmrvictor
  • 683
  • 7
  • 25

2 Answers2

3

it prints only one line

because you use System.out.print(array[i] + " ");,

you can change it to System.out.println(array[i] + " ");

David Walschots
  • 12,279
  • 5
  • 36
  • 59
xingbin
  • 27,410
  • 9
  • 53
  • 103
  • oh no, this is for the data. Because data come as an array. After th,s loop, I also write System.out.println( " "); to go next line. – Beste Iskemleci Oct 03 '18 at 12:11
  • @BesteIskemleci You said `I couldn't do it`. What is the exact problem? – xingbin Oct 03 '18 at 12:16
  • it prints only one line. I want to have all the lines on the console. – Beste Iskemleci Oct 03 '18 at 12:20
  • @Beste Iskemleci You want to write them into the file, also want to print them on console. the problem is, they have been put into the file, but did not appear on the console. Am I Right? – xingbin Oct 03 '18 at 12:34
0

You need a stream to write to the console and to the file at the same time, you can create this stream by using TeeOutputStream part of commons-io giving as a parameter the stream to the console and the stream to the file

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
vmrvictor
  • 683
  • 7
  • 25