java基础回顾--IO流

1.File类的使用

  • java.io.File类:文件和文件目录路径的抽象表示形式,与平台无关
  • File 能新建、删除、重命名文件和目录,但 File 不能访问文件内容本身。
    如果需要访问文件内容本身,则需要使用输入/输出流。
  • 想要在Java程序中表示一个真实存在的文件或目录,那么必须有一个File对 象,但是Java程序中的一个File对象,可能没有一个真实存在的文件或目录
  • File对象可以作为参数传递给流的构造器
1.1路径分隔符
  • 路径中美极目录都用一个路径分隔符相隔开
  • 路径和系统有关:

windows和DOS系统默认使用“\”来表示
UNIX和URL使用“/”来表示

  • 为了解决这个隐患,File类提供了一个常量:
    public static final String separator。根据操作系统,动态的提供分隔符。
File file1 = new File("d:\\dpf\\info.txt");
File file2 = new File("d:" + File.separator + "dpf" + File.separator + "info.txt");
File file3 = new File("d:/dpf");
1.2构造器和常用方法
构造器
  • public File(String pathname) 以pathname为路径创建File对象,可以是绝对路径或者相对路径,如果
    pathname是相对路径,则默认的当前路径在系统属性user.dir中存储。
    绝对路径:是一个固定的路径,从盘符开始
    相对路径:是相对于某个位置开始
  • public File(String parent,String child)
    以parent为父路径,child为子路径创建File对象。
  • public File(File parent,String child)
    根据一个父File对象和子文件路径创建File对象
常用方法
  • public String getAbsolutePath():获取绝对路径
  • public String getPath() :获取路径
  • public String getName() :获取名称
  • public String getParent():获取上层文件目录路径。若无,返回null
  • public long length() :获取文件长度(即:字节数)。不能获取目录的长度。  public long lastModified() :获取最后一次的修改时间,毫秒值
  • public String[] list() :获取指定目录下的所有文件或者文件目录的名称数组
  • public File[] listFiles() :获取指定目录下的所有文件或者文件目录的File数组
  • public boolean renameTo(File dest):把文件重命名为指定的文件路径
  • public boolean isDirectory():判断是否是文件目录
  • public boolean isFile() :判断是否是文件
  • public boolean exists() :判断是否存在
  • public boolean canRead() :判断是否可读
  • public boolean canWrite() :判断是否可写
  • public boolean isHidden() :判断是否隐藏
  • public boolean createNewFile():创建文件。若文件存在,则不创建,返回false
  • public boolean mkdir() :创建文件目录。如果此文件目录存在,就不创建了。
    如果此文件目录的上层目录不存在,也不创建(单层目录文件,多层用mkdirs)。
  • public boolean mkdirs():创建文件目录。如果上层文件目录不存在,一并创建
    注意事项:如果你创建文件或者文件目录没有写盘符路径,那么,默认在项目
    路径下。
  • public boolean delete():删除文件或者文件夹
    删除注意事项:
    Java中的删除不走回收站。 要删除一个文件目录,请注意该文件目录内不能包含文件或者文件目录
File dir1 = new File("D:/IOTest/dir1");
if (!dir1.exists()) { // 如果D:/IOTest/dir1不存在,就创建为目录
dir1.mkdir();
}
// 创建以dir1为父目录,名为"dir2"的File对象
File dir2 = new File(dir1, "dir2");
if (!dir2.exists()) { // 如果还不存在,就创建为目录
dir2.mkdirs();
}
File dir4 = new File(dir1, "dir3/dir4");
if (!dir4.exists()) {
dir4.mkdirs();
}
// 创建以dir2为父目录,名为"test.txt"的File对象
File file = new File(dir2, "test.txt");
if (!file.exists()) { // 如果还不存在,就创建为文件
file.createNewFile();
}

2.IO流

2.1.结构图

在这里插入图片描述

2.2.流基类

字节流
InputStream
  • int read()
    从输入流中读取数据的下一个字节。返回 0 到 255 范围内的 int 字节值。如果因
    为已经到达流末尾而没有可用的字节,则返回值 -1。
  • int read(byte[] b)
    从此输入流中将最多 b.length 个字节的数据读入一个 byte 数组中。如果因为已
    经到达流末尾而没有可用的字节,则返回值 -1。否则以整数形式返回实际读取
    的字节数。
  • int read(byte[] b, int off, int len)
    将输入流中最多 len 个数据字节读入 byte 数组。尝试读取 len 个字节,但读取
    的字节也可能小于该值。以整数形式返回实际读取的字节数。如果因为流位于
    文件末尾而没有可用的字节,则返回值 -1。
  • void close()
    关闭此输入流并释放与该流关联的所有系统资源。
OutputStream
  • void write(int b/int c);
  • void write(byte[] b/char[] cbuf);
  • void write(byte[] b/char[] buff, int off, int len);
  • void flush();
    刷新此输出流并强制写出所有缓冲的输出字节,调用此方法指示应将这些字节立
    即写入它们预期的目标。
  • void close(); 需要先刷新,再关闭此流
字符流
Reader
  • int read()
  • int read(char [] c)
  • int read(char [] c, int off, int len)
  • void close()
Writer
  • void write(String str);
  • void write(String str, int off, int len);
  • void flush();
  • void close(); 需要先刷新,再关闭此流

字节流字符流的选择:

  1. 对于文本文件(.txt,.java,.c,.cpp),使用字符流处理
  2. 对于非文本文件(.jpg,.mp3,.mp4,.avi,.doc,.ppt,…),使用字节流处理

2.3.其他几种流

节点流
  • FileReader
FileReader fr = null;
        try {
            fr = new FileReader(new File("c:\\test.txt"));
            char[] buf = new char[1024];
            int len;
            while ((len = fr.read(buf)) != -1) {
                System.out.print(new String(buf, 0, len));
            }
        } catch (IOException e) {
            System.out.println("read-Exception :" + e.getMessage());
        } finally {
            if (fr != null) {
                try {
                    fr.close();
                } catch (IOException e) {
                    System.out.println("close-Exception :" + e.getMessage());
                }
            }
        }
  • FileWriter
 FileWriter fw = null;
        try {
            fw = new FileWriter(new File("Test.txt"));
            
            //fw = new FileWriter(new File("Test.txt"),true);//追加 
            fw.write("test....");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fw != null)
                try {
                    fw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
        }

1.在写入一个文件时,如果使用构造器FileOutputStream(file),则目录下有同名文件将被覆盖。
2.如果使用构造器FileOutputStream(file,true),则目录下的同名文件不会被覆盖,在文件内容末尾追加内容。

缓冲流
  • BufferedInputStream和 BufferedOutputStream
 BufferedInputStream bis = null;
        BufferedOutputStream bos = null;

        try {

            //构造文件
            File srcFile = new File("testBase/t.jpg");
            File descFile = new File("testBase/t1.jpg");

            //造节点流
            FileInputStream fis = new FileInputStream(srcFile);
            FileOutputStream fos = new FileOutputStream(descFile);

            //造缓冲流
            bis = new BufferedInputStream(fis);
            bos = new BufferedOutputStream(fos);

            //复制的细节:读入、写入
            byte[] buffer = new byte[10];
            int len;
            while ((len = bis.read(buffer))!= -1){
                bos.write(buffer,0,len);
            }

        }catch (IOException e){
            e.printStackTrace();
        } finally {
            //4.资源关闭
            //要求:先关闭外层的流,再关闭内层的流
            if(bos != null){
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
            if(bis != null){
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
            //说明:关闭外层流的同时,内层流也会自动的进行关闭。关于内层流的关闭,我们可以省略.
            //fos.close();
            //fis.close();
        }

  • BufferedReader 和 BufferedWriter
		BufferedReader br = null;
        BufferedWriter bw = null;
        try {
            // 创建缓冲流对象:它是处理流,是对节点流的包装
            br = new BufferedReader(new FileReader("d:\\IOTest\\source.txt"));
            bw = new BufferedWriter(new FileWriter("d:\\IOTest\\dest.txt"));
            String str;
            while ((str = br.readLine()) != null) { // 一次读取字符文本文件的一行字符
                bw.write(str); // 一次写入一行字符串
                bw.newLine(); // 写入行分隔符
            }
            bw.flush(); // 刷新缓冲区
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭IO流对象
            try {
                if (bw != null) {
                    bw.close(); // 关闭过滤流时,会自动关闭它所包装的底层节点流
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (br != null) {
                    br.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

1.当读取数据时,数据按块读入缓冲区,其后的读操作则直接访问缓冲区
2. 当使用BufferedInputStream读取字节文件时,BufferedInputStream会一次性从
文件中读取8192个(8Kb),存在缓冲区中,直到缓冲区装满了,才重新从文件中读取下一个8192个字节数组。
3. 向流中写入字节时,不会直接写到文件,先写到缓冲区中直到缓冲区写满,BufferedOutputStream才会把缓冲区中的数据一次性写到文件里。使用方法flush()可以强制将缓冲区的内容全部写入输出流
4.关闭流的顺序和打开流的顺序相反。只要关闭最外层流即可,关闭最外层流也会相应关闭内层节点流
5.flush()方法的使用:手动将buffer中内容写入文件
5. 如果是带缓冲区的流对象的close()方法,不但会关闭流,还会在关闭流之前刷新缓冲区,关闭后不能再写出

转换流
  • InputStreamReader:将InputStream转换为Reader
  • OutputStreamWriter:将Writer转换为OutputStream
FileInputStream fis = null;
        FileOutputStream fos = null;
        InputStreamReader isr = null;
        OutputStreamWriter osw = null;
        BufferedReader br = null;
        BufferedWriter bw = null;
        try {

            //构建需要转换的字节流对象
            fis = new FileInputStream("1.txt");
            fos = new FileOutputStream("2.txt");

            //构建转换流对象  gbk防止读中文乱码
            isr = new InputStreamReader(fis, "gbk");
            osw = new OutputStreamWriter(fos, "gbk");

            //转换
            br = new BufferedReader(isr);
            bw = new BufferedWriter(osw);

            String str = null;
            while ((str = br.readLine()) != null) {

                bw.write(str);

                bw.newLine();
                bw.flush();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(bw != null){
                try {
                    bw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(br != null){
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

1.字节流中的数据都是字符时,转成字符流操作更高效。
2.很多时候我们使用转换流来处理文件乱码问题。实现编码和解码的功能。

输入输出流
  • System.in和System.out分别代表了系统标准的输入和输出设备
  • 默认输入设备是:键盘,输出设备是:显示器
  • System.in的类型是InputStream
  • System.out的类型是PrintStream,其是OutputStream的子类FilterOutputStream 的子类
打印流
  • PrintStream
  • PrintWriter
  1. 实现将基本数据类型的数据格式转化为字符串输出。
    2.提供了一系列重载的print()和println()方法,用于多种数据类型的输出
    3.PrintStream和PrintWriter的输出不会抛出IOException异常
    4.PrintStream和PrintWriter有自动flush功能
    5.PrintStream 打印的所有字符都使用平台的默认字符编码转换为字节。
    6.在需要写入字符而不是写入字节的情况下,应该使用 PrintWriter 类。
    7.System.out返回的是PrintStream的实例
数据流
  • DataInputStream
  • DataOutputStream
对象流
  • ObjectInputStream
  • OjbectOutputSteam

1.用于存储和读取基本数据类型数据或对象的处理流。它的强大之处就是可以把Java中的对象写入到数据源中,也能把对象从数据源中还原回来
2. 序列化:用ObjectOutputStream类保存基本类型数据或对象的机制。
3. 反序列化:用ObjectInputStream类读取基本类型数据或对象的机制。

序列化
  1. ObjectOutputStream和ObjectInputStream不能序列化static和transient修饰的成员变量。
  2. 对象序列化机制允许把内存中的Java对象转换成平台无关的二进制流,从而允许把这种二进制流持久地保存在磁盘上,或通过网络将这种二进制流传输到另一个网络节点。当其它程序获取了这种二进制流,就可以恢复成原来的Java对象
  3. 序列化的好处在于可将任何实现了Serializable接口的对象转化为字节数据,使其在保存和传输时可被还原
  4. 如果需要让某个对象支持序列化机制,则必须让对象所属的类及其属性是可序列化的,为了让某个类是可序列化的,该类必须实现(Serializable或者Externalizable)两个接口之一。否则,会抛出NotSerializableException异常。
  5. 凡是实现Serializable接口的类都有一个表示序列化版本标识符的静态变量:
    • private static final long serialVersionUID;
    • serialVersionUID用来表明类的不同版本间的兼容性。简言之,其目的是以序列化对象进行版本控制,有关各版本反序列化时 是否兼容。
  6. 如果类没有显示定义这个静态常量,它的值是Java运行时环境根据类的内部细节自
    动生成的。若类的实例变量做了修改,serialVersionUID 可能发生变化。故建议显式声明。
    简单来说,Java的序列化机制是通过在运行时判断类的serialVersionUID来验证版本一致性的。在进行反序列化时,JVM会把传来的字节流中的serialVersionUID与本地相应实体类的serialVersionUID进行比较,如果相同就认为是一致的,可以进行反序列化否则就会出现序列化版本不一致的异常。(InvalidCastException)。
使用对象流序列化对象

1.若某个类实现了 Serializable 接口,该类的对象就是可序列化的:

  • 创建一个 ObjectOutputStream
  • 调用 ObjectOutputStream 对象的 writeObject(对象) 方法输出可序列化对象
  • 注意写出一次,操作flush()一次

2.反序列化

  • 创建一个 ObjectInputStream
  • 调用 readObject() 方法读取流中的对象

3.强调:如果某个类的属性不是基本数据类型或 String 类型,而是另一个引用类型,那么这个引用类型必须是可序列化的,否则拥有该类型的Field 的类也不能序列化。

class Person implements Serializable {
    private static final long serialVersionUID = -1926440181236885191L;
    private String name ;
    private Integer age;
    private String sex;
    public Person(String name, Integer age, String sex) {
        this.name = name;
        this.age = age;
        this.sex = sex;
    }
    public Person(){

    }
    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", sex='" + sex + '\'' +
                '}';
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Integer getAge() {
        return age;
    }
    public void setAge(Integer age) {
        this.age = age;
    }
    public String getSex() {
        return sex;
    }
    public void setSex(String sex) {
        this.sex = sex;
    }
}

 //序列化
    public static void testwriter(){
        ObjectOutputStream oos = null;

        try {
            oos = new ObjectOutputStream(new FileOutputStream("data.txt"));
            Person p = new Person("ls",18,"sex");
            oos.writeObject(p);
            oos.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(oos != null){
                try {
                    oos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    
    //反序列化
    public static void testReader(){
        ObjectInputStream ois = null;

        try {
            ois = new ObjectInputStream(new FileInputStream("data.txt"));
            Person p = (Person)ois.readObject();
            System.out.println(p);

        } catch (Exception e) {
            e.printStackTrace();
        }

    }
随机存储文件流

RandomAccessFile

  • RandomAccessFile直接继承于java.lang.Object类,实现了DataInput和DataOutput接口,也就意味着这个类既可以读也可以写。
  • RandomAccessFile 类支持 “随机访问” 的方式,程序可以直接跳到文件的任意
    地方来读、写文件
    • 支持只访问文件的部分内容
    • 可以向已存在的文件后追加内容
  • RandomAccessFile 对象包含一个记录指针,用以标示当前读写处的位置。RandomAccessFile 类对象可以自由移动记录指针:
    • long getFilePointer():获取文件记录指针的当前位置
    • void seek(long pos):将文件记录指针定位到 pos 位置
  • 构造器
    • public RandomAccessFile(File file, String mode)
    • public RandomAccessFile(String name, String mode)
    • 创建 RandomAccessFile 类实例需要指定一个 mode 参数
    • mode参数:
      • r: 以只读方式打开
      • rw:打开以便读取和写入
      • rwd:打开以便读取和写入;同步文件内容的更新
      • rws:打开以便读取和写入;同步文件内容和元数据的更新
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值