64. 输出字节流(FileOutputStream)

IO分类:
    按照数据流向分类:
        输入流
        
        输出流
    
    按照处理的单位划分:
        字节流:字节流读取的都是文件中的二进制数据,读取到的二进制数据不会经过任何处理
        
        字符流:字符流读取的数据都是以字符为单位的,字符流也是读取的文件的二进制数据,只不过会把这些二进制数据转换成我们能识别的字符
                字符流 =  字节流 + 解码

输出字节流::
------------------|OutputStream  所有输出字节流的基类  抽象类
-----------|FileOutputStream  向文件输出数据的输出字节流  throws FileNotFoundException


FileOutputStream的使用步骤:
    
    1.找到目标文件
    2.建立数据通道
    3.把数据转换成字节数组写出
    4.关闭资源

FileOutputStream的一些方法:

    close()    关闭此文件输出流并释放与此流有关的所有系统资源。
    write(int b)    将指定字节写入此文件输出流。
    write(byte[] b)   将 b.length 个字节从指定 byte 数组写入此文件输出流中。
    write(byte[] b, int off, int len)  将指定 byte 数组中从偏移量 off 开始的 len 个字节写入此文件输出流。
     
    注意:
      1.write(byte b[])方法实际上是调用了 write(byte b[], int off, int len)方法
       
       
       
FileOutputStream要注意的细节:
    
    1.使用FileOutputStream的时候,如果目标文件不存在,那么会创建目标文件对象,然后把数据写入
    2.使用FileOutputStream的时候,如果目标文件已经存在,那么会清空目标文件的数据后再写入数据,如果需要再原数据的上追加数据,需要使用FileOutputStream(file,true)构造函数
    3.使用FileOutputStream的write方法写数据的时候,虽然接受的是一个int类型的数据,但真正写出的只是一个字节的数据,只是把低八位的二进制数据写出,其他二十四位数据全部丢弃

public class Demo2 {
    public static void main(String[] args) {
        
        //1.找到目标文件
        File file = new File("D:\新建文件夹 (2)\a.txt");
        System.out.println("文件的源文数据是:"+readFile(file));
        writeFile(file,"Hello World!");
        System.out.println("目前文件数据是:"+readFile(file));
    }
    //输出数据
    public static void writeFile(File file,String data) {
        FileOutputStream fileOutputStream = null;
        try{
            //2.建立通道(我的源文件数据:abc  追加数据)
            fileOutputStream = new FileOutputStream(file,true);
            //3.把要写入的数据转换成字符数组
            fileOutputStream.write(data.getBytes());
            
        }catch(IOException e) {
            
            throw new RuntimeException(e);
        }finally {
            //关闭资源
            try {
                fileOutputStream.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            
        }
    }
    
    //输入数据
    public static String readFile(File file) {
        FileInputStream  fileInputStream = null;
        String str = "";
        try {
            //建立数据通道
            fileInputStream = new FileInputStream(file);
            //创建缓冲字节数组
            byte[] buf = new byte[1024];
            int length = 0;
            while((length = fileInputStream.read(buf))!=-1) {
                //把字节数组转换成字符串返回
                str+=new String(buf,0,length);
            }
        } catch (IOException e) {
            throw new RuntimeException();
        }finally {
            try {
                fileInputStream.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        return str;
    }
}

原文地址:https://www.cnblogs.com/zjdbk/p/9042805.html