File I/O 文件输入输出流

InputStream:字节输入流(抽象类)--》FileInputStream
int read():
从输入流一个字节一个字节的读,返回的是该字节的整数表示形式,如果到了输入流的末尾,返回-1
int read(byte[ ] b):
从输入流读取若个字节,把这些字节保存到数组b中,返回的是读取到的字节数,如果到了输入流的末尾,返回-1

int read(byte[ ] b , int off , int len):
从输入流读取若个字节,把这些字节保存到数组b中,off指的是字节数组中开始保存数据的起始下标,len指读取的字节数目。返回的是读取到的字节数,如果到了输入流的末尾,返回-1


File类
file.createNewFile()    如果文件存在,则不会创建新文件
file.exists    判断文件是否存在   
dir.mkdir()   创建目录

一、字节流
字节输入流(读)
    InputStream
                   read()
                read(byte[ ])
                read(byte[ ],off,len)
                            close()
    FileInputStream
                new FileInputStream(File file)
                new FileInputStream(String path)
字节输出流(写)
    OutputStream
                write(int)
                            write(byte[ ])
                write(byte[ ],off,len)
                            close()
                flush():强制将缓冲区清空
    FileOutputStream
                new FileOutputStream(File file)
                new FileOutputStream(String path)
                new FileOutputStream(String path,boolean append):可以指定覆盖或追加文件内容
二、字符流

GBK   GB2312
UTF-8

字符输入流(读)
    Reader
                read()
                read(char[ ])
                read(char[ ],off,len)
                            close()
    InputStreamReader : 可以指定字符编码格式
                new InputStreamReader(InputStream)
                            new InputStreamReader(InputStream,String charSetName)
    FileReader
                new FileReader(File file)
                            new FileReader(String path)
    常见问题:中文乱码
    原因:文件编码格式     和      程序环境的编码格式不一致
    
    解决方案:
    字符流去读的时候,指定字符流的编码格式
    FileReader   无法指定编码格式,会按照系统默认编码格式读
    System.out.println(System.getProperty("file.encoding"));
    所以使用InputStreamReader

     缓冲流BufferedReader
    readLine()
    
字符输出流(写)
    Writer
        write(String)
        close()
        flush():清空缓存
    OutputStreamReader : 可以指定字符编码格式
        new OutputStreamWriter(OutputStream)
        new OutputStreamWriter(OutputStream,String charSetName)
    FileWriter:以下两种构造,都可以重载,指定一个boolean类型的参数,用来指定追加还是覆盖文件内容
        new FileWriter(File file)
        new FileWriter(String path)
    
    
    BufferedWriter  :  带缓冲区的输出流

三、二进制文件的读写
DataInputStream
DataOutputStream

四、序列化和反序列化
ObjectInputStream       反序列化   readObject()  -->  类型转换
ObjectOutputStream        序列化      writeObject(Object)

常见异常:
NotSerializableException :  类没有实现Serializable接口,不可被序列化

不想被序列化的属性前面加  transient 屏蔽某些敏感字段的序列化

猜你喜欢

转载自blog.csdn.net/weixin_42425900/article/details/82113614