Extra Characters in ByteArrayOutputStream() result Java [duplicate]

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 is no ‘extra space’. There is a newline, the result of you calling println(). If you don’t want the newline, don’t call a method that produces one. If you’re expecting the string to look the way it would look it Java source code, adjust your expectations. It won’t.

    – 




  • try String t="Hello world!\n"; for(int i =0; i<t.length();i++) { System.out.println(t.charAt(i)+"*"); }

    – 

  • 1

    Replace your manual output with a proper assertion (assertEquals("Hello world!\n", bos.toString());) and you’ll see that the test passes.

    – 

  • When I run your code I don’t see the line with the extra space…

    – 

  • Are you using Windows? Windows uses \r\n for newlines, so this might be the \r?

    – 

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.

Leave a Comment