我有两个文件,test-1.text (内容是Data from test-1)和test-2.text (内容是Data from test-2)。
当我使用SequenceInputStream从两个流读取时,输出要么以一条直线的形式出现,比如Data from test-1Data from test-2,要么每个字符都在新的行上。
如何开始在新行中从第二个流中打印内容?
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);
}}
输出是
Data from test-1Data from test-2
期望输出
Data from test-1
Data from test-2
发布于 2017-07-21 14:44:34
这个响应基于this helpful SO answer,它提供了一种从流集合创建SequenceInputStream的方法。这里的基本思想是,您已经有两个流,它们提供您想要的输出。您只需要一个行中断,更具体地说,一个生成行中断的流。我们可以简单地从换行符的字节中创建一个ByteArrayInputStream,然后将它夹在您已经拥有的文件流之间。
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);发布于 2017-07-21 14:44:07
SequenceInputStream不支持此选项。修复此列表以向文件test-1.text ( content:Data from test-1\n)的内容添加换行符('\n')的唯一方法
https://stackoverflow.com/questions/45240421
复制相似问题