Java IO流

Io

File

文件和目录路径名的抽象表示。

java.io.File

Io流分类

IO:数据的读入写出,文件的上传下载
流:一连串流动的数据,以先入先出的方式进行传输–>流就是管道

 数据源---->io---->目的地
 数据源 : 数据的来源
 目的地 : 数据流向的位置

流的分类:

操作单元分:
  字节流:万能流 *****
  字符流:纯文本内容
  流向分: 以程序为中心
            输入流
            输出流
功能分:
 节点流 : 真实能做读入写出的
 功能流 : 增强节点流的功能,提高节点流的性能

流之间的分类是相辅相成的

 java.io包

InputStream 字节输入流中最上层父类

文件流 : FileInputStream 文件字节输入流->节点流  字节流  输入流
        操作文件,数据源为文件,使用文件字节输入流
字节数组流 : ByteArrayInputStream 字节数组输入流 ->节点流  字节流  输入流
           操作字节数组,数据源是字节输入,使用字节数组输入流

代码:

public static void main(String[] args) throws IOException {
        File src=new File("D://test.txt");
        //FileInputStream(File file) 通过打开与实际文件的连接来创建 FileInputStream ,该文件由文件系统中的 File对象 file命名。
        InputStream is=new FileInputStream(src);
        //读入 int read() 每次读入一个字节数,返回读入到的字节,读不到返回-1
       // int num=is.read();
       /* System.out.println((char) num);
        System.out.println((char)is.read());
        System.out.println((char)is.read());
        System.out.println(is.read());

       //循环读入
        /*int num = -1; //记录每次读到的字节
        while((num=is.read())!=-1){
            System.out.println((char)num);
        }*/

        //提高效率,每次读入一车(字节数组)的数据
        //byte[] car = new byte[1024];
        //int read(byte[]) 每次读入一个字节数组的数据,返回读入到字节数组中数据的个数,没有读到返回-1
        //int len = is.read(car);
        //System.out.println(new String(car,0,len));

        //当内容比较多,需要重复读入,每次读入一个字节数组中的数据
        /*byte[] car = new byte[2];
        int len = -1; //记录每次读入到数组中数据的个数
        while((len = is.read(car))!=-1){
            System.out.println(new String(car,0,len));
        }*/

        //byte[] readAllBytes() 从输入流中读取所有剩余字节。
        byte[] arr = is.readAllBytes();
        System.out.println(new String(arr));
        //关闭
        is.close();
    }

OutputStream 字节流输出流

    FileOutputStream 文件字节输出流 -> 节点流
        目的地为文件
    ByteArrayOutputStream 字节数组输出流 -> 节点流
        目的地为字节数组

注意: 在输出流写出的时候,如果目的地文件不存在,系统会自动创建目的地文件,如果目的地文件所在路径不存在,抛出异常java.io.FileNotFoundException:(系统找不到指定的路径。)

代码:

public static void main(String[] args) throws IOException {
        //创建流,指定目的地
        OutputStream os=new FileOutputStream("D://test2.txt");
        //2.写出
        os.write(97);
        //3.刷出
        os.flush();
        //4.关闭
        os.close();
    }

字节流实现文件拷贝: *****

   数据源-->输入流-->程序-->输出流-->目的地

步骤:
1.构建流(输入流 输出流)
2.读入写出
3.刷新
4.关闭(后打开的先关闭)
代码:

InputStream is=null;
OutputStream os=null;
        try {
            //1.构建流
             is=new FileInputStream("D://test.txt");
             os=new FileOutputStream("D://DDD//test.txt");
            //2.读入写出
            byte[] car=new byte[1024];
            int len=-1;
            while ((len=is.read(car))!=-1){
                os.write(car,0,len);
            }
            //3.刷出
            os.flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            //4.关闭
            if (os!=null){
                try {
                    os.close();
                }catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (is!=null){
                try {
                    is.close();
                }catch (IOException e) {
                    e.printStackTrace();
              }
        }
  }

字符流 (纯文本数据)

Reader  字符输入流
     FileReader 文件字符输入流  ->节点流
Writer  字符输出流
     FileWriter 文件字符输出流  ->节点流
通过字符流实现文件拷贝

代码:

 public static void main(String[] args) throws IOException {
        //1.构建流
        Reader rd=new FileReader("D://test.txt");
        Writer wr=new FileWriter("D://dest.txt");
        //2.读入写出
        char[] car=new char[1024];
        int len=-1;
        while ((len=rd.read(car))!=-1){
            wr.write(car,0,len);
        }
        //3.刷新
        wr.flush();
        //4.
        wr.close();
        rd.close();
    }

功能流

使用:包裹节点流使用
缓冲流 Buffered : 加快节点流的读写效率
字节缓冲流 :
字节输入缓冲流 BufferedInputStream
字节输出缓冲流 BufferedOutputStream
无新增方法,可以发生多态
字符缓冲流
代码:

 //1.构建流
        InputStream is=new BufferedInputStream(new FileInputStream("D://test.txt"));
        OutputStream os=new BufferedOutputStream(new FileOutputStream("D://test1.txt"));
        //2.读入写出
        byte[] car=new byte[1024];
        int len=-1;
        while ((len=is.read(car))!=-1){
            os.write(car,0,len);
        }
        //3.刷新
        os.flush();
        //4.关闭
        os.close();
        is.close();
字符流缓冲流
    字符输入缓冲流 BufferedReader
        新增功能: String readLine() 读一行文字。
    字符输出缓冲流 BufferedWriter
        新增功能: void newLine() 写一个行分隔符。

    存在新增功能,不能发生多态

代码:

//构建流
        BufferedReader rd=new BufferedReader(new FileReader("D://test.txt"));
        BufferedWriter wd=new BufferedWriter(new FileWriter("D://dest.txt"));
        //读入写出
        String msg=null;
        while ((msg=rd.readLine())!=null){
            wd.write(msg);
            wd.newLine();
        }
        //刷新
        wd.flush();
        //关闭
        wd.close();
        rd.close();

功能流 :

Data流 | 基本数据类型流 : 读写数据+保留数据类型->基本数据类型|字符串
       是字节流的功能流
    DataInputStream     Data输入流
            新增功能 : readXxx()
    DataOuutputStream   Data输出流
            新增功能 : writeXxx()

代码:

public class Class003_DataInputStream {
    public static void main(String[] args) throws IOException {
        read("D:\\haha.txt");
    }
    public static void wirte(String path) throws IOException {
        //构建输出流
        DataOutputStream os = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(path)));
        //准备数据
        int i=100;
        char ch='a';
        boolean flog=false;
        String msg="刘亦菲";
        //写出
        os.writeInt(i);
        os.writeChar(ch);
        os.writeBoolean(flog);
        os.writeUTF(msg);
        //刷新
        os.flush();
        //关闭
        os.close();

    }
    public  static  void  read(String path) throws IOException {
        //构建流
        DataInputStream is=new DataInputStream(new BufferedInputStream(new FileInputStream(path)));
        //读入
       int i =is.readInt();
       char ch =is.readChar();
       boolean flog =is.readBoolean();
       String msg =is.readUTF();
       //处理数据
        System.out.println(i);
        System.out.println(ch);
        System.out.println(flog);
        System.out.println(msg);
        //关闭
        is.close();
    }
}

Object

Object流|对象流|引用数据类型流

    字节流的功能流
    ObjectInputStream   反序列化输入流
        新增方法  Object readObject() 从ObjectInputStream中读取一个对象。  等等
    ObjectOutputStream  序列化输出流
        新增方法 void writeObject(Object obj) 将指定的对象写入ObjectOutputStream。

序列化: 将对象数据转为可存储或者可传输的状态的过程

    不是所有类型的数据都能序列化 java.io.Serializable
        如果写出的对象类型没有实现序列化接口,会遇到运行时异常java.io.NotSerializableException
    序列化与反序列化顺序保持一致
    不是所有的属性都需要序列化 transient
    static的成员不会被序列化
    如果父类实现类序列化接口,子类所有内容都可以进行序列化
    子类实现了序列化接口,只能序列化子类独有的内容

序列号: 当实现了序列化的类型默认存在一个序列号

    当类中的成员发生改变,序列号默认会重新生成

作用: 使用序列号可以实现检查前后版本不一致问题

    解决不同版本的兼容问题: 手动设置序列号

通过快捷键生成序列号:

        1.类型必须实现了序列化接口
        2.Setting中进行配置
        3.双击类名alt+enter,自动生成序列号  

代码:

public class Class004_Obect {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        testOut("D://test.txt");
        testIn("D://test.txt");

    }

    //序列化输出
    public  static void testOut(String path) throws IOException {
        //输出流
        ObjectOutputStream os=new ObjectOutputStream(new FileOutputStream(path));
        //准备数据
        int[] arr={1,2,3,4,5};
        Person p=new Person("刘亦菲",18,1001);
        //写出
        os.writeObject(arr);
        os.writeObject(p);
        //刷出
        os.flush();
        //关闭
        os.close();
    }
    //反序列化输出
    public  static void testIn(String path) throws IOException, ClassNotFoundException {
        //构建输出流
        ObjectInputStream is=new ObjectInputStream(new FileInputStream(path));
        //读入
        int[] arr= (int[]) is.readObject();
        Person p= (Person) is.readObject();

        //处理数据
        System.out.println(p);
        System.out.println(Arrays.toString(arr));
        //关闭
        is.close();

    }
}
class  Person implements Serializable{
    private static final long serialVersionUID = -1108656603703788489L;
    private   String name;
    private  int age;
    private int ID;

    public Person() {
    }

    public Person(String name, int age, int ID) {
        this.name = name;
        this.age = age;
        this.ID = ID;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public int getID() {
        return ID;
    }

    public void setID(int ID) {
        this.ID = ID;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", ID=" + ID +
                '}';
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Person person = (Person) o;
        return age == person.age && ID == person.ID && Objects.equals(name, person.name);
    }

}

CommonsIO

CommonsIO 是apache的一个开源的工具包,封装了IO操作的相关类,使用Commons IO可以很方便的读写文件,url源代码等。
是一个第三方的开源组件

使用第三方组件的步骤:

    1.对应官网中下载源码 jar
    2.在项目下新建一个文件夹目录lib,lib下存放以后项目所依赖的所有jar包
    3.选中jar包,右键add as lib...
    4.在项目下对应类中进行使用

代码:

public class Class001_CommonsIO {
    public static void main(String[] args) throws IOException {
        //#### IO工具类IOUtils
        //`IOUtils.copy(InputStream input, OutputStream output) `// 此方法有多个重载方法,满足不同的输入输出流
        IOUtils.copy(new FileInputStream("D://test.txt"),new FileOutputStream("D://xixi.txt"));

    //IO 工具类 FilenameUtils
    //`FilenameUtils.getBaseName(String filename)` // 去除目录和后缀后的文件名
    System.out.println(FilenameUtils.getBaseName("D://test.txt"));
    //`FilenameUtils.getExtension(String filename)` // 获取文件的后缀
    System.out.println(FilenameUtils.getExtension("D://logo.png"));
    //`isExtension(String fileName, String text) `// 判断fileName是否是text后缀名
    System.out.println(FilenameUtils.isExtension("D://logo.jpg","png"));

    //IO 工具类 FileUtils
    //`FileUtils.copyFile(File srcFile, File destFile)` // 复制文件
    FileUtils.copyFile(new File("D://test.txt"), FileUtils.getFile("D://hehe.txt"));

    //`FileUtils.copyFileToDirectory(File srcFile, File destDir)` // 复制文件到一个指定的目录
    FileUtils.copyFileToDirectory(new File("D://test.txt"), new File("D://eee")); //目标路径不存在,也可以帮助创建

    //`FileUtils.writeStringToFile(File file, String data, String encoding, boolean append)`// 指定知否追加
    FileUtils.writeStringToFile(new File("D://test.txt"), "\r\nwangwuwuwuwuwuwuwu", "UTF-8",true);
    //`FileUtils.deleteDirectory(File directory)` // 删除文件夹,包括文件夹和文件夹里面所有的文件
    FileUtils.deleteDirectory(new File("D://DDD"));

    //`FileUtils.copyDirectory(File srcDir, File destDir)` // 复制文件夹(文件夹里面的文件内容也会复制)
    FileUtils.copyDirectory(new File("D://AAA"), new File("D://BBB"));

    //`FileUtils.copyDirectoryToDirectory(File srcDir, File destDir)` // 以子目录的形式将文件夹复制到到另一个文件夹下
    FileUtils.copyDirectoryToDirectory(new File("D://AAA"), new File("D://BBB"));

    //`FileUtils.copyDirectory(File srcDir, File destDir, FileFilter filter)` // 复制文件夹,带有文件过滤功能
    FileUtils.copyDirectory(new File("D://AAA"), new File("D://HAHA"), FileFilterUtils.fileFileFilter());
}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值