I have two files, test-1.text (content is Data from test-1) and test-2.text (content is Data from test-2).
when I use SequenceInputStream to read from two streams, output comes either in one straight line like Data from test-1Data from test-2 or every character is on new line.
How can I start to print content from the second stream in 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 is
Data from test-1Data from test-2
Desired output
Data from test-1
Data from test-2
I based this response on this helpful SO answer which provides a method for creating a SequenceInputStream from a collection of streams. The basic idea here is that you already have two streams which give the output you want. You only need a line break, more specifically a stream which generates a line break. We can simply create a ByteArrayInputStream from the bytes of a newline string, and then sandwich it in between the file streams 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);
SequenceInputStream doesn't support this option. The only way to fix that ist to add a newline ('\n') character to the content of the file test-1.text (content: Data from test-1\n)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With