第十七章:IO流

本文详细介绍了Java中文件的创建、删除、信息获取,以及字节流和字符流的使用,包括FileInputStream、FileOutputStream、BufferedReader、BufferedWriter等。还展示了如何进行文件拷贝、序列化和反序列化,以及Properties类的使用。内容涵盖文件的基本操作和IO流的多种应用场景。
摘要由CSDN通过智能技术生成

一、文件流:

 二、常用的文件操作:

new File(String pathname) //根据路劲创建一个File对象

new File(File parent, String child) //根据父目录文件+子路劲构建

new File(String parent,String chile) //根据父目录+子路径构建

使用createNewFile()创建新文件

//方式一 new File(String pathname)
    @Test
    public void create1(){
        String filePath = "d:\\news3.txt";
        File file = new File(filePath);
        try {
            file.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("创建成功");
    }
    //方式二 new File(File parent, String child)
    @Test
    public void create2(){
        File parentFile = new File("e:\\");
        String fileName= "news.txt";
        File file = new File(parentFile,fileName);
        try {
            file.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //方法三  new File(String parent,String chile)
    @Test
    public void create3(){
        String parentPath = "e:\\";
        String fileName = "news3.txt";
        File file = new File(parentPath,fileName);
        try {
            file.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

三、获取文件信息

@Test
    public void info(){
        //先创建文件对象
        File file = new File("d:\\news.txt");

        //调用相应的方法,得到对应的信息
        System.out.println("文件名字:"+file.getName());
        System.out.println("获取文件绝对路劲:"+file.getAbsolutePath());
        System.out.println("获取父级目录"+file.getParent());
        System.out.println("获取文件大小(字节):"+file.length());
        System.out.println("判断文件是否存在:"+file.exists());
        System.out.println("是不是一个文件:"+file.isFile());
        System.out.println("是不是一个目录:"+file.isDirectory());
    }

四、目录的操作

@Test
    public void m1() {
        //判断文件是否存在,存在就删除
        String filePath = "d:\\news1.txt";
        File file = new File(filePath);
        if (file.exists()) {
            if (file.delete()) {
                System.out.println("删除成功");
            } else {
                System.out.println("删除失败");
            }
        } else {
            System.out.println("该文件不存在");
        }
    }

    @Test
    public void m2() {
        //判断文件目录,存在就删除 , 在java中,目录也被当成文件
        String filePath = "d:\\demo";
        File file = new File(filePath);
        if (file.exists()) {
            if (file.delete()) {
                System.out.println("删除成功");
            } else {
                System.out.println("删除失败");
            }
        } else {
            System.out.println("该目录不存在");
        }
    }

    @Test
    public void m3() {
        //判断文件目录是否存在,不存在就创建
        String filePath = "d:\\demo";
        File file = new File(filePath);
        if (file.exists()) {
            System.out.println("该目录不存在");
        } else {
            if (file.mkdir()) { //创建多级目录使用 mkdirs
                System.out.println("创建成功");
            }else{
                System.out.println("创建失败");
            }
        }
    }

五、IO的原理与分类

输入input:读取外部数据(磁盘,光盘等存储设备的数据)到程序(内存)中

输出output:将程序(内存) 数据输出到磁盘、光盘等存储设备中

按操作数据单位不同分为:字节流(8 bit) 二进制文件字符流(按字符)文本文件

抽象基类                        字节流                        字符流

输入流                        InputStream                  Reader

输出流                        OutputStream               Writer

六、字节流

(1)FileInputStream (外面的文件到程序):

@Test
    public void readFile01() {
        String filePah = "d:\\news123.txt";
        int readData = 0;
        FileInputStream fileInputStream = null;
        try {
            //创建 FileInputStream 对象 用于读取 文件
            fileInputStream = new FileInputStream(filePah);
            //返回-1,表示读取完毕
            while ((readData = fileInputStream.read()) != -1) {
                System.out.print((char) readData); //转成char显示
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //关闭文件流,释放资源
            try {
                fileInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 演示读取文件。。。
     * 单个字节的读取,效率比较低
     * ->使用read(byte[] b ) 读取提高效率
     * new String(buf,0,buf.length) 第一个参数为char数组,第二个参数开始位置,第三个参数为结束位置
     */
    @Test
    public void readFile02() {
        String filePah = "d:\\news123.txt";
        int readLen = 0;
        //定义字节数组
        byte[] buf = new byte[8]; //一次读取8个字节
        FileInputStream fileInputStream = null;
        try {
            //创建 FileInputStream 对象 用于读取 文件
            fileInputStream = new FileInputStream(filePah);
            //返回-1,表示读取完毕
            while ((readLen = fileInputStream.read(buf)) != -1) {
                System.out.println(new String(buf,0,buf.length));
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //关闭文件流,释放资源
            try {
                fileInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

(2)FileOutputStream(程序写到外部文件):

注意:如果写的文件不存在它会自动创建

/**
     * 演示OutputStream 将数据写道文件中
     * 如果该文件不存在,则创建
     */
    @Test
    public void writeFile(){
        //创建FileOutputStream对象
        String filePath = "d:\\news123.txt";
        FileOutputStream fileOutputStream = null;

        try {
            //new FileOutputStream(filePath); 会覆盖原来的内容
            //new FileOutputStream(filePath,true); 创建方式时追加到文件后面
            fileOutputStream = new FileOutputStream(filePath,true);
            //写入一个字节
//            fileOutputStream.write('H');//写入一个a试试
            //写入字符串
            String str = "hello,world";
//            //str.getByes转化为字符数组
//            fileOutputStream.write(str.getBytes()); //方法一
            fileOutputStream.write(str.getBytes(),0,str.length());
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                fileOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

(3)案例文件拷贝:

@SuppressWarnings({"all"}) //取消文件警告
public class Hello {
    public static void main(String[] args) {
        String oldFilePah = "d:\\avatar.jpg";
        String newFilePah = "d:\\avatar(1).jpg";
        int readLen = 0;
        byte[] buf = new byte[1024];
        FileOutputStream fileOutputStream = null;
        FileInputStream fileInputStream = null;
        try {
            fileInputStream = new FileInputStream(oldFilePah);
            fileOutputStream = new FileOutputStream(newFilePah);
            while ((readLen = fileInputStream.read(buf)) != -1){
               fileOutputStream.write(buf,0, readLen);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                fileInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                fileOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

七、字符流

(1)FileReader(读取文件字符流到程序):

@Test
    /**
     * 单个字符读取
     */
    public void readFile1(){
        String filePath = "d:\\news123.txt";
        int data = ' ';
        FileReader fileReader = null;
        try {
            fileReader = new FileReader(filePath);
            while ((data = fileReader.read()) != -1){
                System.out.print((char) data);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                fileReader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Test
    /**
     * 多个字符的读取
     */
    public void readFile2(){
        String filePath = "d:\\news123.txt";
        char[] buf = new char[8];
        int readLen = 0;
        FileReader fileReader = null;
        try {
            fileReader = new FileReader(filePath);
            //循环读取 使用read(buf),返回的时实际读取到的字符数
            //如果返回-1,说明文件结束
            while ((readLen = fileReader.read(buf)) != -1){
                System.out.print(new String(buf,0,readLen));
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                fileReader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

(2)FileWriter(读取程序字符流到文件):

注意:new FileWriter(File/String,true) //表示追加    new FileWriter(File/String) //表示覆盖

@Test
    public void writeFile(){
        String filePath = "d:\\news123.txt";
        String str = "风雨之后,定见彩虹";
        FileWriter fileWriter = null;
        try {
            fileWriter = new FileWriter(filePath); //直接覆盖
            fileWriter = new FileWriter(filePath,true); //追加
            fileWriter.write(str,0,str.length());
            //在数量大的时候使用循环
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                fileWriter.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

八、处理流

(1)BufferReader(读取文件到程序):

public static void main(String[] args) throws IOException {
        String filePath = "d:\\news123.txt";
        //创建bufferedReader
        BufferedReader bufferedReader = new BufferedReader(new FileReader(filePath));
        //读取
        String line;// bufferedReader.readLine(); 按行读取效率高
        //当返回null的时候表示读取完毕
        while ((line = bufferedReader.readLine())!= null){
            System.out.print(line);
        }
        //关闭流,只需要关闭外层流
        bufferedReader.close();
    }

 (2) BufferWriter(读取程序到文件):

public static void main(String[] args) throws IOException {
        String filePath = "d:\\news123.txt";
        //创建BufferedWriter  FileWriter(filePath) ,第二个参数表示是否追加
        BufferedWriter bufferedWriter= new BufferedWriter(new FileWriter(filePath));
        bufferedWriter.write("hello,张三");
        bufferedWriter.newLine();//插入一个换行符
        bufferedWriter.close();
    }

(3)案例文件的拷贝:

 //文件的拷贝
    public static void main(String[] args) throws IOException {
        String filePath = "d:\\news123.txt";
        String filePath2 = "d:\\news456.txt";
        String line;
        BufferedReader bufferedReader = new BufferedReader(new FileReader(filePath));
        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(filePath2));
        while ((line = bufferedReader.readLine()) != null){
            bufferedWriter.write(line);
        }
        bufferedReader.close();
        bufferedWriter.close();
    }

(4)BufferedOutputSream字节处理流(程序写到文件):

(5)BuffereInputStream字节处理流(文件到程序):

 //文件的拷贝
    //字节流可以操作二进制文件(图片,视频),可以操作文本文件
    public static void main(String[] args) throws IOException {
        String filePath = "d:\\news123.txt";
        String filePath2 = "d:\\news456.txt";

        BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(filePath));
        BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(filePath2));

        byte[] buff = new byte[1024];
        int readLen = 0;
        while ((readLen = bufferedInputStream.read(buff)) != -1){
            bufferedOutputStream.write(buff,0,readLen);
        }

        bufferedInputStream.close();
        bufferedOutputStream.close();
    }

(6)ObjectOutputStream(程序到文件):序列化到文件

序列化和反序列化:序列化就是在保存数据时,保存数据的值和数据类型。反序列化就是在恢复数据时,恢复数据的值和数据类型。要支持序列化需要实现Serializable//标记接口(用这个)  Externailzable(这恶鬼不常用)

 public static void main(String[] args) throws IOException {
        //序列化后,保存的文件格式,不是存文本,而是按照他的格式来保存
        String filePath = "d:\\news12.dat";
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(filePath));
        //序列化数据到 d:\\news12.dat
        oos.write(100); //int --- Integer (实现 serializable)
        oos.writeBoolean(true); //boolean  --  Boolean(实现 serializable)
        oos.writeDouble(100.9); //double -- Double (实现 serializable)
        oos.writeUTF("韩顺平教育"); //String
        oos.close();
        System.out.println("序列化完成");
    }

(7)ObjectInputStream(文件到程序):反序列化到程序

public static void main(String[] args) throws IOException {
        //指定反序列化的文件
        String filePath = "d:\\news12.dat";
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream(filePath));
        //反序列化,读取的顺序要和保存数据的顺序一致。否则会报异常
        System.out.println(ois.readInt());
        System.out.println(ois.readBoolean());
        System.out.println(ois.readDouble());
        System.out.println(ois.readUTF());
    }

(8)标准输入输出流:

system.out.print()   system.in

九、转换流

当处理纯文本数据时,如果使用字符流效率更高,并且可以有效解决中文乱码,所以建议将字节流转换成字符流。在使用时可以指定编码

(1)InputStreamReader(文件读取到程序):

public static void main(String[] args) throws IOException {
        String filePath = "d:\\news123.txt";
        //1.把FileInputStream 转成  InputStreamReader
        //2.指定编码 gdk
        InputStreamReader inputStreamReader = new InputStreamReader(new FileInputStream(filePath),"gbk");
        //3.把 InputStreamReader 传入  BufferedReader(isr)
        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
        //4.读取
        String s = bufferedReader.readLine();
        System.out.println("读取到的是:" + s);
        ///5.关闭外层
        bufferedReader.close();
    }

(2)OutputStreamWriter(程序到文件):

public static void main(String[] args) throws IOException {
        String filePath = "d:\\news123.txt";
        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(new FileOutputStream(filePath),"utf-8");
        outputStreamWriter.write("hi,韩顺平教育");
        outputStreamWriter.close();
    }

十、Properties类

  1. load:加载配置文件的键值对到Properties对象
  2. list:将数据显示到指定设备
  3. getProperty(key):根据键获取值
  4. setProperty(key,value):根据键值对到Properies对象
  5. store:将Properties中的键值对存储到配置文件,在Idea中,保存信息到配置文件,如果含有中文,会存储为unicode码

(1)Properties读取文件:

public static void main(String[] args) throws IOException {
        //使用Properies 类来读取配置文件
        //1.创建Properies对象
        Properties properties = new Properties();
        //2.加载指定文件
        properties.load(new FileReader("d:\\news123.txt"));
        //3.把k-v显示在控制台
        properties.list(System.out);
        //4.根据key 获取对应的值
        String id = properties.getProperty("id");
        String name = properties.getProperty("name");
        System.out.println("id:"+id+" name:"+name);
    }

(2)Properties修改文件:

public static void main(String[] args) throws IOException {
        //使用Properies 类来创建配置文件,修改配置文件
        Properties properties = new Properties();
        //创建
        //如果该文件没有key,就是创建
        //如果该文件右key,就是修改
        properties.setProperty("charset","utf8");
        properties.setProperty("user","root");
        properties.setProperty("psw","root");
        //将k-v存储文件  null表示unicode码
        properties.store(new FileOutputStream("d:\\news123.txt"),null);
    }

十一、课后作业

 public static void main(String[] args) throws IOException {
        String dirctory = "d:\\mytemp";
        File file = new File(dirctory);
        if (!file.exists()){
            if (file.mkdir()){
                System.out.println("创建成功");
            }else{
                System.out.println("创建失败");
            }
        }

        String filePath = dirctory+"\\hello.txt";
        File file1 = new File(filePath);
        if (!file1.exists()){
            if (file1.createNewFile()){
                System.out.println("创建成功");
            }else{
                System.out.println("创建失败");
            }
        }
    }

public static void main(String[] args) throws IOException {
        String filePath = "d:\\news123.txt";
        BufferedReader bufferedReader = new BufferedReader(new FileReader(filePath));
        String str = "";
        int i = 0;
        while((str = bufferedReader.readLine()) != null) {
            i++;
            System.out.println(i + ". " + str);
        }
    }

@SuppressWarnings({"all"}) //取消文件警告
public class Hello {
    public static void main(String[] args) throws IOException {
        String filePath = "d:\\news123.txt";
        Properties properties = new Properties();
        properties.load(new FileInputStream(filePath));
        String name = properties.getProperty("name");
        String color = properties.getProperty("color");
        int age = Integer.parseInt(properties.getProperty("age"));
        Dog dog = new Dog(name, color, age);
        System.out.println(dog);
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(filePath));
        objectOutputStream.writeObject(dog);
        objectOutputStream.close();
    }
}

class Dog implements Serializable{
    String name;
    String color;
    int age;

    public Dog(String name, String color, int age) {
        this.name = name;
        this.color = color;
        this.age = age;
    }

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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值