New line for each new stream in SequenceInputStream

I have two files: test-1.text

(content Data from test-1

) and test-2.text

(content Data from test-2

).
when i use SequenceInputStream

to read from two streams, the output comes either on one straight line of type Data from test-1Data from test-2

or each character is on a new line.
How do I start printing content from the second stream on a new line?

public class SequenceIStream {

public static void main(String[] args) throws IOException {
    FileInputStream fi1 = new FileInputStream("resources/test-1.text");
    FileInputStream fi2 = new FileInputStream("resources/test-2.text");

    SequenceInputStream seq = new SequenceInputStream(fi1, fi2);

    int i= 0;

    while((i = seq.read())!=-1)
        System.out.print((char)i);
}

      

}

Output
Data from test-1Data from test-2

Desired output
Data from test-1


Data from test-2

+3


source to share


2 answers


I based this answer on this helpful SO answer which provides a method to create SequenceInputStream

from a collection of streams. The basic idea here is that you already have two threads that give you the result you want. You only need a line break, more specifically the stream that generates the line break. We can simply create ByteArrayInputStream

newlines from the bytes and then sandwich between the file streams that you already have.



FileInputStream fi1 = new FileInputStream("resources/test-1.text");
FileInputStream fi2 = new FileInputStream("resources/test-2.text");

String newLine = "\n";
List<InputStream> streams = Arrays.asList(
    fi1,
    new ByteArrayInputStream(newLine.getBytes()),
    fi2);
InputStream seq = new SequenceInputStream(Collections.enumeration(streams));

int i= 0;

while((i = seq.read())!=-1)
    System.out.print((char)i);

      

+4


source


SequenceInputStream does not support this option. The only way to fix it ist to add a newline character ( '\ n') to the contents of the file test-1.text

(content: Data from test-1\n

)



+1


source







All Articles