上节中我们简单的了解了如何将文件内容作为字节流读取。本节我们来说说上节提到的FileOutputStream
。
FileOutputStream
类是OutputStream
的子类,其用于输出原始字节流,如图片视频等。
public class FileOutputStream extends OutputStream {}
FileOutputStream
类是OutputStream
的子类,其用于输出原始字节流,如图片视频等。Java API提供了5种构造器,分析源代码可以得出,无论是使用字符串类型的文件名,还是使用File对象来创建连接,最终都是利用文件描述符来建立连接。
//创建文件输出流以写入具有指定名称的文件
public FileOutputStream(String name) throws FileNotFoundException {}
//创建文件输出流以写入具体指定名称的文件,若append为true则字节将写入文件的末尾而不是开头
public FileOutputStream(String name, boolean append) throws FileNotFoundException{}
//创建文件输出流以写入由指定的File对象表示的文件
public FileOutputStream(File file) throws FileNotFoundException {}
//创建文件输出流以写入由指定的File对象表示的文件,若append为true则字节将写入文件的末尾而不是开头
public FileOutputStream(File file, boolean append) throws FileNotFoundException {}
//创建要写入指定文件描述符的文件输出流,该文件描述符表示与文件系统中实际文件的现有连接
public FileOutputStream(FileDescriptor fdObj) {}
在FileInputStream
中Java API提供了read()
方法用于读取字节,而FileOutputStream
中Java API提供了write()
方法用于写入字节。
//将指定的字节写入此文件输出流中
public void write(int b) throws IOException {}
//将指定字节数组中b.length个字节写入此文件输出流
public void write(byte b[]) throws IOException {}
//将从off开始的指定字节数组中len个字节写入此文件输出流
public void write(byte b[], int off, int len) throws IOException {}
//示例
public class RSD_OutputStream {
public static void main(String[] args) {
try {
FileOutputStream fos = new FileOutputStream("D:/fileOutputStream.txt", true);
fos.write("Hello World".getBytes());
} catch (FileNotFoundException e) {
//若因为其他原因无法打开(如设置不可写),则抛出此异常
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
无论是在使用输入流
FileInputStream
还是使用输出流FileOutputStream
,都需要在最后对流进行关闭,用于释放与此流关联的所有系统资源。
//关闭输入流
fis.close();
//关闭输出流
fos.close();
纸上得来终觉浅,绝知此事要躬行。——陆游《冬夜读书示子聿》
这里我们只是简单的介绍了两种常用的流处理方式,在项目开发中,我们也许会引入第三方的各类JAR包,其中也存在某些JAR包对字节流类做详细处理,因此我们需要活学活用。比如在JSP页面中显示我们在文档服务器中的文件时,我们需要使用到OutputStream
类的子类ServletOutputStream
类来写入流文件,并通过ServletResponse
接口的getOutputStream()
方法返回ServletOutputStream
类的实例。