转载地址:https://mp.weixin.qq.com/s/C1a2ig6poXch4bdYocVStw
https://mp.weixin.qq.com/s/_zWUFv_IZ5Jb8OUMmpO75A
-
SequenceInputStream类在Java中IO流的体系结构图的位置
-
为什么要引入SequenceInputStream类?
在软件的日常运行中,会生成一些日志文件,记录软件的使用情况,这些文件通常几天生成一个,为方便管理,需要定期合并,可以使用SequenceInputStream实现。 其缺点在于没有充分利用文本文件的特性。 -
什么是SequenceInputStream类?
是Java SE中IO流体系中的字节输入流InputStream的子类。
-
SequenceInputStream类的特点和作用
SequenceInputStream可以看做是多个InputStream对象的有序集合。当一个InputStream对象的数据读取完后,它会自动取出下一个InputStream对象进行读取,直到所有的InputStream对象都读取完为止。 -
SequenceInputStream的所有已知实现的接口
所有已实现的接口:Closeable
-
常用SequenceInputStream类的构造方法
-
常用SequenceInputStream类的成员方法
-
举例
-
int read() ; 从此输入流中读取下一个数据字节。
java.io.SequenceInputStream.read() 方法读取当前输入流中数据的下一个字节。该字节被返回为一个范围在0到255之间的整数,如果没有可用的字节,因为流的末尾已到达,则返回值-1。此方法一直阻塞在输入数据可用,该流的末尾被检测到,或者抛出一个异常。
public class SequenceInputStreamDemo {
public static void main(String[] args) {
// create two new strings with 5 characters each
String s1 = "Hello";
String s2 = "World";
// create 2 input streams
byte[] b1 = s1.getBytes();
byte[] b2 = s2.getBytes();
ByteArrayInputStream byteArrayInputStream1 = new ByteArrayInputStream(b1);
ByteArrayInputStream byteArrayInputStream2= new ByteArrayInputStream(b2);
// create a new Sequence Input Stream
SequenceInputStream sequenceInputStream =
new SequenceInputStream(byteArrayInputStream1, byteArrayInputStream2);
try {
// read 10 characters, 5 from each stream
for (int i = 0; i < 10; i++) {
char c = (char) sequenceInputStream.read();
System.out.print("" + c);
}
// change line
System.out.println();
// close the streams
sequenceInputStream.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
-
输出结果为:
HelloWorld -
int read(byte[] b, int off, int len) ; 将最多 len 个数据字节从此输入流读入 byte 数组。
java.io.SequenceInputStream.read(byte[] b,int off,int len) 方法读取最多len个从这个输入流中数据的字节到字节数组。如果len不为零,则该方法阻塞,直到输入最少1个字节是可用的;否则,不读取任何字节并返回0。
public class SequenceInputStreamDemo {
public static void main(String[] args) {
// create two new strings with 5 characters each
String s1 = "Hello";
String s2 = "World";
// create 2 input streams
byte[] b1 = s1.getBytes();
byte[] b2 = s2.getBytes();
ByteArrayInputStream byteArrayInputStream1 = new ByteArrayInputStream(b1);
ByteArrayInputStream byteArrayInputStream2 = new ByteArrayInputStream(b2);
// create a new Sequence Input Stream
SequenceInputStream sequenceInputStream =
new SequenceInputStream(byteArrayInputStream1, byteArrayInputStream2);
// create a new byte array
byte arr[] = {'1', '2', '3', '4'};
try {
// read 3 chars and print the number of chars read
System.out.print("" + sequenceInputStream.read(arr, 0, 3));
// change line
System.out.println();
// close the streams
sequenceInputStream.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
-
输出结果为
3
本文版权归(Java从入门到架构师)作者和微信公众平台共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接,否则保留追究法律责任的权利。