Extra Characters in ByteArrayOutputStream() result Java

49 Views Asked by At

java

public class Hello {
        public static void main(final String[] args) {
            System.out.println("Hello world!");
        }

}

Class to test the result:

import static org.junit.jupiter.api.Assertions.assertEquals;

import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;

import java.io.*;

public class TestHello {

    @Test
    public void testHelloWorld()
    {
        System.out.println("Test started");
        PrintStream originalOut = System.out;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        System.setOut(new PrintStream(bos));

        // action
        Hello.main(null);

        // undo the binding in System
        System.setOut(originalOut);

        //result check
        String t=bos.toString();
        for(int i =0; i<t.length();i++){
            System.out.println(t.charAt(i)+"*");
        }
        System.out.println(t.length());

        System.out.println("Test ended");
    }
}

Output:

Test started 
H* 
e* 
l* 
l* 
o*  
* 
w* 
o* 
r* 
l* 
d* 
!*
 *

 * 
14 
Test ended

How to get rid of space between * and * above 14. Is there a way to do this in better way, so that this extra character will not appear?

Ideally t="Hello world!\n", but that's not the case.

1

There are 1 best solutions below

0
Lajos Arpad On

You have

System.out.println(t.charAt(i)+"*");

and you will need to make sure that you only println it if it's appropriate. For example, you could have something like this in your loop:

char somechars[] = {'\n', '\r'};

and then

if (somechars.indexOf(t.charAt(i)) == -1) System.out.println(t.charAt(i)+"*");

so if your blacklist of chars you don't want to show contains the character, then you don't print it, otherwise you print it.