Day19--(File、字符集、I/O流(一))

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~   

一.  File

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~  

1.   概述和创建对象

    public static void main(String[] args) {

         //1.创建 File三种方式
        File f = new File("E:\\桌面\\EDG.jpg");
        File f1 = new File("E:/桌面/EDG.jpg");
        File f2 = new File("E:"+File.separator+"桌面"+File.separator+"EDG.jpg");
        
        // 2、File创建对象,支持绝对路径 支持相对路径(重点)
        File F1 = new File("D:\\resources\\beauty.jpeg"); // 绝对路径
        System.out.println(F1.length());

        // 相对路径:一般定位模块中的文件的。 相对到工程下!!
        File F = new File("Test模块/src/Date.txt");
        System.out.println(F.length());

        // 3、File创建对象 ,可以是文件也可以是文件夹
        File f3 = new File("D:\\resources");
        System.out.println(f3.exists()); // 判断这个路径是否存在,这个文件夹存在否
        
        File F4 = new File("Test模块/src/Date.txt");
        System.out.println(F4.length());
    }

2.  File类的常用API

①  判断文件类型、获取文件信息

 API 代码演示:

    public static void main(String[] args) {
        // 1.绝对路径创建一个文件对象
        File f1 = new File("D:/resources/xueshan.jpeg");

        // a.获取它的绝对路径。
        System.out.println(f1.getAbsolutePath());

        // b.获取文件定义的时候使用的路径。
        System.out.println(f1.getPath());

        // c.获取文件的名称:带后缀。
        System.out.println(f1.getName());

        // d.获取文件的大小:字节个数。
        System.out.println(f1.length()); // 字节大小

        // e.获取文件的最后修改时间
        long time = f1.lastModified();
        System.out.println("最后修改时间:" + new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(time));

        // f、判断文件是文件还是文件夹
        System.out.println(f1.isFile()); // true
        System.out.println(f1.isDirectory()); // false

        System.out.println("-------------------------------------------------");

        File f2 = new File("Test模块\\src\\data.txt");
        // a.获取它的绝对路径。
        System.out.println(f2.getAbsolutePath());//D:\Code\总代码\Test模块\src\data.txt

        // b.获取文件定义的时候使用的路径。
        System.out.println(f2.getPath());// Test模块\src\data.txt
    }

②  创建文件、删除文件功能

 API 代码演示: 

    public static void main(String[] args) throws IOException {
     
        // a.创建新文件,创建成功返回true ,反之 ,不需要这个,以后文件写出去的时候都会自动创建
        File f1 = new File("file-io-app\\src\\data02.txt");
        System.out.println(f1.createNewFile()); // (几乎不用的,因为以后文件都是自动创建的!)

        // b.mkdir创建一级目录
        File f2 = new File("D:/resources/aaa");
        System.out.println(f2.mkdir());

        // c.mkdirs创建多级目录(重点)
        File f3 = new File("D:/resources/ccc/ddd/eee/ffff");
        System.out.println(f3.mkdirs()); // 支持多级创建

        // d.删除文件或者空文件夹
        System.out.println(f1.delete());
        File f4 = new File("D:/resources/xueshan.jpeg");
        System.out.println(f4.delete()); // 占用一样可以删除

        // 只能删除空文件夹,不能删除非空文件夹.
        File f5 = new File("D:/resources/aaa");
        System.out.println(f5.delete());
    }

③  遍历文件夹 

API代码演示:

    public static void main(String[] args) throws IOException {

        // 1、定位一个目录
        File f = new File("E:/AAA");

        //2. list方法
        String[] list = f.list();
        System.out.println(Arrays.toString(list));//  [BBB, CCC, DDD]

        //3.  listFiles方法
        File f2 = new File("E:/AAA ");
        File[] files = f2.listFiles();
        for (File file : files) {
            System.out.println(file.getAbsolutePath());
        }

        System.out.println(Arrays.toString(files));
        //[E:\AAA \BBB, E:\AAA \CCC, E:\AAA \DDD]
    }

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 

 二.   字符集

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

1.常见字符集介绍

  

2.  字符集的编码、解码操作

代码演示: 

    public static void main(String[] args) throws Exception {
        // 1、编码:把文字转换成字节(使用指定的编码)
        String name = "abc我爱你中国";
        byte[] bytes1 = name.getBytes(); // 以当前代码默认字符集进行编码 (UTF-8)
        byte[] bytes2 = name.getBytes("GBK"); // 指定编码

        System.out.println(bytes1.length);
        System.out.println(Arrays.toString(bytes1));

        // 2、解码:把字节转换成对应的中文形式(编码前 和 编码后的字符集必须一致,否则乱码 )
        String rs1 = new String(bytes1); // 默认的UTF-8
        String rs2 = new String(bytes1, "GBK"); // 指定GBK解码
        System.out.println(rs1);
    }

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~   

三. I/O 流

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~  

1.  概述

 

 2.    字节流的使用

① 文件字节输入流:FileInputStream

  

 代码演示:

    public static void main(String[] args) throws Exception {
        // 1.  读取一个字节返回 (每次读取一滴水)
        InputStream is = new FileInputStream("Test模块/src/Date.txt");

        int b;
        while ((b = is.read()) != -1) {
            System.out.print((char) b);
        }

        //2. 定义一个字节数组,用于读取字节数组
        byte[] buffon = new byte[3];
        int len;
        while ((len = is.read(buffon)) != -1) {
            System.out.print(new String(buffon, 0, len));
        }

        //3.  定义一个字节数组与文件的大小刚刚一样大   ,读取全部字节数组
        byte[] buffer1 = is.readAllBytes();
        System.out.println(new String(buffer1));
    }

② 文件字节输出流:FileOutputStream

  代码演示:

public class OutputStreamDemo04 {
    public static void main(String[] args) throws Exception {
        // 1、创建一个文件字节输出流管道与目标文件接通
        OutputStream os = new FileOutputStream("file-io-app/src/out04.txt" , true); // 追加数据管道
//        OutputStream os = new FileOutputStream("file-io-app/src/out04.txt"); // 先清空之前的数据,写新数据进入

        // 2、写数据出去
        // a.public void write(int a):写一个字节出去
        os.write('a');
        os.write(98);
        os.write("\r\n".getBytes()); // 换行
        // os.write('徐'); // [ooo]

        // b.public void write(byte[] buffer):写一个字节数组出去。
        byte[] buffer = {'a' , 97, 98, 99};
        os.write(buffer);
        os.write("\r\n".getBytes()); // 换行

        byte[] buffer2 = "我是中国人".getBytes();
//        byte[] buffer2 = "我是中国人".getBytes("GBK");
        os.write(buffer2);

        // c. public void write(byte[] buffer , int pos , int len):写一个字节数组的一部分出去。
        byte[] buffer3 = {'a',97, 98, 99};
        os.write(buffer3, 0 , 3);// 写 ‘a’  97 98 出去
      
        // os.flush(); // 写数据必须,刷新数据 可以继续使用流
        os.close(); // 释放资源,包含了刷新的!关闭后流不可以使用了
    }
}

3. 资源释放的方式

①.  try-catch-finally

文件拷贝结合 Finally :

public class TryCatchFinallyDemo1 {
    public static void main(String[] args) {
        InputStream is = null;
        OutputStream os = null;
        try {

            // System.out.println(10/ 0);

            // 1、创建一个字节输入流管道与原视频接通
            is = new FileInputStream("E:\\资料\\黑马java\\第1阶段—Java SE基础\\1、Java基础--20天学会Java\\20天学会java—视频\\day19、File、递归、IO流(一)\\01、今日课程安排、File概述、File对象的创建.mp4");

            // 2、创建一个字节输出流管道与目标文件接通
            os = new FileOutputStream("E:/视频.mp4");

            // 3、定义一个字节数组转移数据
            byte[] buffer = new byte[1024];
            int len; // 记录每次读取的字节数。
            while ((len = is.read(buffer)) != -1) {
                os.write(buffer, 0, len);
            }
            System.out.println("复制完成了!");

              System.out.println( 10 / 0);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 无论代码是正常结束,还是出现异常都要最后执行这里
            System.out.println("========finally=========");
            try {
                // 4、关闭流。
                if (os != null) os.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                if (is != null) is.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        System.out.println(test(10, 2));
    }

    public static int test(int a, int b) {
        try {
            int c = a / b;
            return c;
        } catch (Exception e) {
            e.printStackTrace();
            return -111111; // 计算出现bug.
        } finally {
            System.out.println("--finally--");
            // 哪怕上面有return语句执行,也必须先执行完这里才可以!
            // 开发中不建议在这里加return ,如果加了,返回的永远是这里的数据了,这样会出问题!
            return 100;
        }
    }
}

②. try-with-resource

 简化代码演示:

    //   JDK7  简化
    public static void main(String[] args) throws Exception {

        try (
                InputStream in = new FileInputStream("E:\\资料\\黑马java\\第1阶段—Java SE基础\\1、Java基础--20天学会Java\\20天学会java—视频\\day19、File、递归、IO流(一)\\01、今日课程安排、File概述、File对象的创建.mp4");
                OutputStream ou = new FileOutputStream("E:/视频.mp4");
        ) {
            System.out.println("~~~~~~~~~~~~~~~~~~");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

//------------------------------------------------------------------------------------//
    //   JDK9  简化
    public static void main(String[] args) throws Exception {
        InputStream in = new FileInputStream("E:\\资料\\黑马java\\第1阶段—Java SE基础\\1、Java基础--20天学会Java\\20天学会java—视频\\day19、File、递归、IO流(一)\\01、今日课程安排、File概述、File对象的创建.mp4");
        OutputStream ou = new FileOutputStream("E:/视频.mp4");
        try (in; ou) {
            System.out.println("~~~~~~~~~~~~~~~~~~");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

4. 字符流的使用

① 文件字符输入流

API 代码演示: 

    public static void main(String[] args) throws Exception {
        // 目标:每次读取一个字符。
        Reader fr = new FileReader("file-io-app\\src\\data06.txt");
        
        // 使用循环读取字符
        int code;
        while ((code = fr.read()) != -1){
            System.out.print((char) code);
        }
    }
//------------------------------------------------------------------------------//
    public static void main(String[] args) throws Exception {
          // 目标:每次读取一个字符数组
       
        Reader fr = new FileReader("file-io-app/src/data07.txt");

        //  循环,每次读取一个字符数组的数据。  1024 + 1024 + 8
        char[] buffer = new char[1024]; // 1K字符
        int len;
        while ((len = fr.read(buffer)) != -1) {
            String rs = new String(buffer, 0, len);
            System.out.print(rs);
        }

    }


 ② 文件字符输出流

 API 代码演示:

public class FileWriterDemo03 {
    public static void main(String[] args) throws Exception {
        // 1、创建一个字符输出流管道与目标文件接通
        // Writer fw = new FileWriter("file-io-app/src/out08.txt"); // 覆盖管道,每次启动都会清空文件之前的数据
        Writer fw = new FileWriter("file-io-app/src/out08.txt", true); // 覆盖管道,每次启动都会清空文件之前的数据

//      a.public void write(int c):写一个字符出去
        fw.write(98);
        fw.write('a');
        fw.write('徐'); // 不会出问题了
        fw.write("\r\n"); // 换行

//       b.public void write(String c)写一个字符串出去
        fw.write("abc我是中国人");
        
//       c.public void write(char[] buffer):写一个字符数组出去
        char[] chars = "abc我是中国人".toCharArray();
        fw.write(chars);
        
//       d.public void write(String c ,int pos ,int len):写字符串的一部分出去
        fw.write("abc我是中国人", 0, 5);

//       e.public void write(char[] buffer ,int pos ,int len):写字符数组的一部分出去
        fw.write(chars, 3, 5);

        // fw.flush();// 刷新后流可以继续使用
        fw.close(); // 关闭包含刷线,关闭后流不能使用

    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值