Beste Iskemleci
Beste Iskemleci

Reputation: 13

How to convert console data to text file in Java

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

Upvotes: 1

Views: 779

Answers (2)

vmrvictor
vmrvictor

Reputation: 723

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

Upvotes: 0

xingbin
xingbin

Reputation: 28289

it prints only one line

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

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

Upvotes: 3

Related Questions