FileOutputStream(文件字节输出流)
作用:以内存为基准,把内存中的数据以字节的形式写出到文件中去
构造器 | 说明 |
public FileOutputStream(File file) | 创建字节输出流管道与源文件对象接通 |
public FileOutputStream(String filepath) | 创建字节输出流管道与源文件路径接通 |
public FileOutputStream(File file,boolean append) | 创建字节输出流管道与源文件对象接通,可追加数据 |
public FileOutputStream(String filepath,boolean append) | 创建字节输出流管道与源文件路径接通,可追加数据 |
方法名称 | 说明 |
publicvoid write(int a) | 写一个字节出去 |
public void write(byte[ ]buffer) | 写一个字节数组出去 |
public void write(byte[ ]buffer,int pos,int len) | 写一个字节数组的一部分出去 |
public void close() throws IOException | 关闭流。 |
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
//目标:掌握文件字节输出流FileOutStream的使用
public class OutputStream1 {
public static void main(String[] args) throws IOException {
//创建一个字节输出流管道与目标文件接通
// OutputStream os=new FileOutputStream("D:\\code\\weilai1\\src\\itheima1.txt");
//追加数据的管道
OutputStream os=new FileOutputStream("D:\\code\\weilai1\\src\\itheima1.txt",true);
//开始写字节数组出去了
os.write(97);
os.write('b');
byte[] bytes="我爱你abc".getBytes();
os.write(bytes,0,9);
os.write(bytes);
//换行符
os.write("\r\n".getBytes());
//关闭流
os.close();
}
}
字节流非常适合做一切文件的复制操作
任何文件的底层都是字节,字节流做复制,是一字不漏的转移完全部的字节,只要复制后的文件格式一致就没问题
try-catch-finally
try{
...
}catch (IOException e){
e.printStackTrace( )
}finally{
}
finally代码区的特点:无论try中的程序是正常执行了,还是出现了异常,最后都一定会执行finally区,除非JVM终止。
作用:一般用于在程序执行完成后进行资源的释放操作(专业级做法)。
JDK7开始提供了更简单的资源释放方案: try-with-resource
try(定义资源1;定义资源2;...){
可能出现异常的代码;
}catch(异常类名 变量名){
异常的处理代码;}
该资源使用完毕后,会自动调用其close0方法,完成对资源的释放!
()中只能放置资源,否则报错
什么是资源呢?
资源一般指的是最终实现了AutoCloseable接口。
public abstract class InputStream implements Closeable{ }
public abstract class OutputStream implements Closeable,Flushable { }
public interface Closeable extends AutoCloseable { }
import java.io.*;
public class OutputStream2 {
//使用字节流完成对文件的复制操作
public static void main(String[] args) {
//需求:复制照片
//创建一个文件字节输入流管道和源文件接通
try (InputStream is = new FileInputStream("G:\\heima1\\新建文件夹");
OutputStream os = new FileOutputStream("F:\\My Java\\图片\\新建文件夹");
//注意:这里只能放置资源对象(流对象)
//什么是资源呢?
//资源都会实现AutoCloseable接口的,资源都会有一个close方法,并且资源放到这里被用完之后,
// 会自动调用close方法完成资源的释放操作
){
//创建一个字节数组,负责转移字节数据
byte[]bytes=new byte[1024];
//从字节输入流中读取字节数据,再写到字节输出流中去,读多少写出去多少
int len;//记住每次读取了多少个字节
while ((len=is.read(bytes))!=-1){
os.write(bytes,0,len);
}
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("复制完成");
}
}