Java中的OutputStream类是一个抽象类,它是所有输出流的父类。OutputStream类提供了一些抽象方法,它们用于将字节写入输出流中。在本篇文章中,我们将详细介绍Java中的OutputStream类,并提供一些代码示例。
一、OutputStream类的继承关系
OutputStream类是一个抽象类,它有很多子类,例如:
- ByteArrayOutputStream
- FileOutputStream
- PipedOutputStream
- FilterOutputStream
OutputStream类和其子类提供了不同的功能,可以用于将字节写入不同的数据源中,例如内存、文件或管道。
二、OutputStream类的常用方法
OutputStream类提供了很多方法,这里我们介绍其中一些常用的方法:
public void write(int b) throws IOException
将指定的字节写入此输出流,b为要写入的字节。
OutputStream os = new FileOutputStream("example.txt");
os.write(65); //写入字符A的ASCII码
os.close(); //关闭输出流
public void write(byte[] b) throws IOException将b.length个字节从指定的字节数组写入此输出流。
OutputStream os = new FileOutputStream("example.txt");
byte[] b = {'H', 'e', 'l', 'l', 'o', '!', '\n'};
os.write(b); //写入字节数组
os.close(); //关闭输出流
public void write(byte[] b, int off, int len) throws IOException将len个字节从指定的字节数组开始,从偏移量off开始写入此输出流。
OutputStream os = new FileOutputStream("example.txt");
byte[] b = {'H', 'e', 'l', 'l', 'o', '!', '\n'};
os.write(b, 1, 4); //写入字节数组从下标1开始的4个字节,即"ello"
os.close(); //关闭输出流
public void flush() throws IOException刷新此输出流并强制任何缓冲的输出字节被写出。
OutputStream os = new FileOutputStream("example.txt");
String str = "Hello, World!";
byte[] b = str.getBytes();
os.write(b);
os.flush(); //将缓冲的字节全部写出
os.close(); //关闭输出流
public void close() throws IOException关闭此输出流并释放与此流相关联的任何系统资源。
OutputStream os = new FileOutputStream("example.txt");
os.close(); //关闭输出流
三、OutputStream子类的使用
OutputStream类有很多子类,这里介绍其中一些常用的子类。
1. FileOutputStream
FileOutputStream类是OutputStream类的一个子类,它用于将字节写入文件中。
try {
OutputStream os = new FileOutputStream("example.txt");
String str = "Hello, World!";
byte[] b = str.getBytes();
os.write(b);
os.close();
} catch (IOException e) {
e.printStackTrace();
}
2. ByteArrayOutputStream
ByteArrayOutputStream类是OutputStream类的一个子类,它将字节写入到内存中的byte数组中。
OutputStream os = new ByteArrayOutputStream();
String str = "Hello, World!";
byte[] b = str.getBytes();
os.write(b);
byte[] result = ((ByteArrayOutputStream) os).toByteArray(); //获取写入的字节
os.close();
3. PipedOutputStream
PipedOutputStream类是OutputStream类的一个子类,它可以与PipedInputStream类配合使用,用于线程之间的通信。
PipedOutputStream pos = new PipedOutputStream();
PipedInputStream pis = new PipedInputStream(pos);
new Thread(() -> {
try {
OutputStream os = new FileOutputStream("example.txt");
byte[] b = pis.readAllBytes();
os.write(b);
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}).start();
String str = "Hello, World!";
byte[] b = str.getBytes();
pos.write(b);
pos.close();
总结
本文介绍了Java中的OutputStream类,包括其继承关系、常用方法和子类的使用。OutputStream类是所有输出流的父类,它提供了一些抽象方法,用于将字节写入输出流中。具体使用时,可以根据需要选择其子类,例如FileOutputStream、ByteArrayOutputStream和PipedOutputStream。
原创文章,作者:小蓝,如若转载,请注明出处:https://www.506064.com/n/304684.html
微信扫一扫
支付宝扫一扫