25. File、递归、IO流

File类概述

 

public class Test {
    public static void main(String[] args) {
        // 创建 File对象(指定了文件的路径)
        // 文件名可以是绝对路径,也可以是相对路径
        File f = new File("C:\\Users\\pan\\Desktop\\picture\\1.jpeg");
        File f1 = new File("Learn/src/Picture/1.jpeg");
        System.out.println(f1.length());
        System.out.println(f.length());

        // File创建对象,可以是文件也可以是文件夹
        File f2 = new File("C:\\Users\\pan\\Desktop\\picture");
        System.out.println(f2.exists());
    }
}

File类常用API

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

public class Test {
    public static void main(String[] args) {
        // 1.绝对路径创建一个文件对象
        File f1 = new File("Learn/src/Picture/1.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());
        System.out.println(f1.isDirectory());
    }
}

创建文件、删除文件功能

public class Test {
    public static void main(String[] args) throws IOException {
        File file = new File("Learn/src/Picture/f1.txt");
        // a.创建新文件,创建成功返回true ,反之 ,不需要这个,以后文件写出去的时候都会自动创建
        System.out.println(file.createNewFile());
        // b.mkdir创建一级目录
        File file2 = new File("D:/aaa/aaa");
        System.out.println(file2.mkdir());
        // c.mkdirs创建多级目录(重点)
        File file3 = new File("D:/aaa/aaa/bbbb");
        System.out.println(file3.mkdirs());
        // d.删除文件或者空文件夹
        System.out.println(file3.delete());
        System.out.println(file2.delete());
        // 只能删除空文件夹,不能删除非空文件夹.
    }
}

 

遍历文件夹

public class Test {
    public static void main(String[] args) throws IOException {
        // 1、定位一个目录 只能定义一级文件对象
        File f1 = new File("D:/picture");
        String[] names = f1.list();
        for (String name : names) {
            System.out.println(name);
        }

        // 2.一级文件对象
        // 获取当前目录下所有的"一级文件对象"到一个文件对象数组中去返回(重点)
        File[] files = f1.listFiles();
        for (File f : files) {
            System.out.println(f.getAbsolutePath());
        }
    }
}

方法递归

递归的形式与特点

public class Test {
    public static void main(String[] args) throws IOException {
        test();
    }

    public static void test() {
        System.out.println("===========test被执行===============");
        test(); //方法递归:直接递归形式
    }

    public static void test1() {
        System.out.println("===========test1被执行===============");
        test2(); //方法递归:间接递归
    }

    private static void test2() {
        System.out.println("===========test2被执行===============");
        test1();
    }
}

递归的算法流程、核心要素

public class Test {
    public static void main(String[] args) {
        System.out.println(jc(5));

    }

    public static int jc(int n) {
        if(n == 1) {
            return 1;
        } else {
            return jc(n - 1) * n;
        }
    }
}

递归常见案例

public class Test {
    public static void main(String[] args) throws {
        System.out.println(jc(100));

    }

    public static int jc(int n) {
        if (n == 1) {
            return 1;
        } else {
            return jc(n - 1) + n;
        }
    }
}

递归的经典问题

public class Test {
    public static void main(String[] args) {
        System.out.println(f(1));
    }

    public static int f(int n) {
        if (n == 10) {
            return 1;
        } else {
            return 2 * f(n+1) +2;
        }
    }
}

非规律化递归案例-文件搜索

 

public class Test {
    public static void main(String[] args) {
        // 2. 传入目录和文件夹
        searchFile(new File("D:/") ,"aaa");
    }

    /**
     * 1. 搜索某个目录下的全部文件,找到目标文件
     * @param dir 被搜索的原目录
     * @param fileName 被搜索的文件名称
     */
    public static void searchFile(File dir ,String fileName) {
        // 3. 判断dir是否是文件夹
        if (dir.isDirectory() && (dir != null)) {
            // 开始找
            // 4. 遍历文件夹:提取当前目录下的一级文件对象
            File[] files = dir.listFiles(); //null
            // 5. 判断是否存在一级文件对象
            if (files != null && (files.length > 0)) {
                for (File f : files) {
                    // 6. 判断当前遍历的一级文件是否为文件夹
                    if (f.isFile()) {
                        // 7. 是否是目标文件 ,是输出文件路径
                        if (f.getName().contains(fileName)) {
                            System.out.println("路径为:" + f.getAbsolutePath());
                        }
                    }else {
                        // 是文件夹,需要递归寻找
                        searchFile(f ,fileName);
                    }
                }
            }
        }else {
            System.out.println("当前搜索的不是文件夹");
        }
    }
}

非递归化文件案例-啤酒问题

public class Test {

    // 定义一个静态的成员变量用于存储可以买的酒数量
    public static int totalNumber; // 总数量
    public static int lastBottleNumber; // 剩余瓶子个数
    public static int lastCoverNumber; // 剩余瓶盖个数

    public static void main(String[] args) {
        // 1. 拿钱买酒
        buy(10);
        System.out.println("总数: " + totalNumber);
        System.out.println("盖子数: " + lastCoverNumber);
        System.out.println("瓶子数: " + lastBottleNumber);
    }

    public static void buy(int money) {
        // 2. 看立马能买多少瓶酒
        int buyNumber = (money / 2); //5瓶酒
        totalNumber += buyNumber;
        // 3. 把盖子和瓶子换算成钱
        // 统计本轮盖子数和瓶子数
        int coverNumber = lastCoverNumber + buyNumber;
        int bottleNumber = lastBottleNumber + buyNumber;

        // 统计可以换算的钱
        int allMoney = 0;
        if (coverNumber >= 4) {
           allMoney += (coverNumber / 4) * 2;
        }
        lastCoverNumber = coverNumber % 4;

        if (bottleNumber >= 2) {
           allMoney += (bottleNumber / 2) * 2;
        }
        lastBottleNumber = bottleNumber % 2;

        if (allMoney >= 2) {
            buy(allMoney);
        }
    }
}

字符集

常见字符集介绍

 

字符集的编码、解码操作

public class Test {
    public static void main(String[] args) throws UnsupportedEncodingException {
        // 编码:把文字转换成字节(使用指定的编码)
        String s = "abc我爱你";
        byte[] bytes = s.getBytes("GBK"); // 以当前代码默认字符集进行编码(UTF-8)
        System.out.println(bytes.length);
        System.out.println(Arrays.toString(bytes));

        // 2. 把字节转换成对应的中文形式(编码前 和 编码后的字符集必须一致)
        String rs = new String(bytes ,"GBK"); // 以当前代码默认字符集进行解码(UTF-8)
        System.out.println(rs);
    }
}

IO流概述

字节流的使用

文件字节输入流:每次读取一个字节

public class Test {
    public static void main(String[] args) throws Exception {
        // 创建一个文件字节输入流(管道)
        InputStream input = new FileInputStream("F:\\Windows\\Test File\\Java\\Learn\\src\\Picture\\f1.txt");

        // 读取一个字节返回(每次读取一个字节)
        char b1 = (char) input.read(); // 读取文件返回-1
        // 定义一个变量记录每次读取的字节
        int b;
        while ((b = input.read()) != -1) {
            System.out.print((char) b);
        }
    }
}

文件字节输出流:每次读取一个字节数组

public class Test {
    public static void main(String[] args) throws Exception{
        // 创建一个文件字符输入流管道与源文件接通
        InputStream input = new FileInputStream("F:\\Windows\\Test File\\Java\\Learn\\src\\Picture\\f1.txt");
        int len; // 记录每次读取一个字节数组
        byte[] buffer = new byte[3]; // 每次读3个字节
        while ((len = input.read(buffer)) != -1) {
            System.out.print(new String(buffer, 0,len));
        }
    }
}

文件字节输入流:一次读完全部字节

 

public class Test {
    public static void main(String[] args) throws Exception{
        // 创建一个文件字符输入流管道与源文件接通
        File f = new File("F:\\Windows\\Test File\\Java\\Learn\\src\\Picture\\f1.txt");
        InputStream input = new FileInputStream(f);

        // 定义一个字节数组与文件大小一样大
//        byte[] buffer = new byte[(int) f.length()];
//        int len = input.read(buffer);
//        System.out.println("读取了" + len + "个字节");
//        System.out.println("文件大小:" + f.length());
//        System.out.println(new String(buffer));

        byte[] buffer1 = input.readAllBytes();
        System.out.print(new String(buffer1));
    }
}

文件字节输出流:写字节数据到文件

 

public class Test {
    public static void main(String[] args) throws Exception {
        // 1、创建一个文件字节输出流管道与目标文件接通
        OutputStream output = new FileOutputStream("F:\\Windows\\Test File\\Java\\Learn\\src\\Picture\\2.txt",true);

        // b.public void write(byte[] buffer):写一个字节数组出去。
        output.write('a');
        output.write(98);
        output.write("\n\r".getBytes());
        //output.write('我'); false

        byte[] buffer = {'a' , 89 ,99};
        output.write(buffer);

        //写数据必须刷新数据
        output.flush(); //刷新之后可以使用

        byte[] buffer2 = "我是".getBytes();
        output.write(buffer2); //支持中文


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

文件拷贝

public class Test {
    public static void main(String[] args) {
        // 定义一个字节输入流管道与原视频接通
        try {
            InputStream is = new FileInputStream("src/Picture/2.mp4");

            // 创建一个字节流输出管道与目标文件接通
            OutputStream os = new FileOutputStream("src/Picture/f1.mp4");

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

            //关闭流
            is.close();
            os.close();

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

 

资源释放的方式

try-catch-finally

public class Test {
    public static void main(String[] args) {
            // 创建一个字节流输出管道与目标文件接通
            InputStream is = null;
            // 定义一个字节数组来转移数据
            OutputStream os = null;
        // 定义一个字节输入流管道与原视频接通
        try {
            is = new FileInputStream("src/Picture/2.mp4");
            os = new FileOutputStream("src/Picture/f1.mp4");
            byte[] buffer = new byte[1024];
            int len; //记录每次读取的字节数
            while ((len = is.read()) != -1) {
                os.write(buffer , 0 ,len);
            }
            System.out.println("复制完成");

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 无论代码是否正常结束,finally始终都要最后执行这里
            System.out.println("=========finally==========");

            //关闭流
            try {
                if (is != null)is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (os != null)os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

try-catch-resource

 

public class Test {
    public static void main(String[] args) {
        // 定义一个字节输入流管道与原视频接通
        try (
                //这里只能放资源对象,用完自动关闭资源
                InputStream is = new FileInputStream("src/Picture/2.mp4");
                OutputStream os = new FileOutputStream("src/Picture/f1.mp4");
                
                ){

            byte[] buffer = new byte[1024];
            int len; //记录每次读取的字节数
            while ((len = is.read()) != -1) {
                os.write(buffer , 0 ,len);
            }
            System.out.println("复制完成");

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

 

字符流的使用

文件字符输入流-一次读取一个字符

public class Test {
    public static void main(String[] args) throws Exception{
        // 创建一个字符输入流管道与源文件接通
        Reader fr = new FileReader("Learn\\src\\Picture\\f1.txt");

        // 读取字符
        int code;
        while ((code = fr.read()) != -1) {
        System.out.print((char) code);
        }

    }
}

文件字符输入流-一次读取一个字符数组

public class Test {
    public static void main(String[] args) throws Exception{
        // 创建一个字符输入流管道与源文件接通
        Reader fr = new FileReader("Learn\\src\\Picture\\f1.txt");

        // 定义一个字符数组
        char[] buffer = new char[1024]; //1k字符
        int len; //记录每次读取的字符长度

        // 开始读取字符
        while ((len = fr.read(buffer)) > 0) {
            String rs = new String(buffer ,0 ,len);
            System.out.print(rs);
        }
    }
}

文件字符输出流

 

public class Test {
    public static void main(String[] args) throws Exception{
        // 创建一个字符输入流管道与源文件接通
       // Reader fr = new FileReader("Learn\\src\\Picture\\f1.txt");
        Writer fw = new FileWriter("F:\\Windows\\Test File\\Java\\Learn\\src\\Picture\\2.txt");

        //写一个字符出去
        fw.write('a');
        fw.write(89);

        //写一个字符串出去
        fw.write("abc老王");

        //写一个字符串数组出去
        char[] chars = "abcasd老王".toCharArray();
        fw.write(chars);

        //写一个字符串的一部分出去
        fw.write("asdqwe哈哈哈" ,0 ,3);

        //写一个字符串数组一部分出去
        fw.write(chars , 0 ,3);

        //刷新缓存区
        fw.flush();
        fw.close();
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
引用\[1\]:在给定的示例中,使用System.IO命名空间中的File类来创建、写入和读取文件。首先,使用File.Create方法创建一个文件,并使用FileStream来写入一些文本信息到文件中。然后,使用File.OpenText方法打开文件,并使用StreamReader逐行读取文件内容。最后,将读取的内容打印到控制台上。 引用\[2\]:在第二个示例中,使用JavaFile类来打印指定目录下的文件树形结构。首先,判断给定的路径是否合法,如果是文件,则直接打印文件名;如果是目录,则使用递归的方式遍历目录下的文件和子目录,并打印出树形结构。 引用\[3\]:在第三个示例中,使用System.IO命名空间中的File类来移动文件。首先,使用File.Create方法创建一个文件,然后使用File.Move方法将文件移动到指定的目标路径。移动完成后,检查原始文件是否存在,如果存在则打印出错误信息,如果不存在则打印出移动成功的信息。 根据你的问题,IO File file是一个不完整的表达,无法确定具体指的是哪个示例中的代码。请提供更多的上下文或明确的问题,以便我能够给出更准确的回答。 #### 引用[.reference_title] - *1* *3* [【.Net实用方法总结】 整理并总结System.IO中File类及其方法介绍](https://blog.csdn.net/baidu_33146219/article/details/126445772)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* [IO及File介绍](https://blog.csdn.net/m0_46853673/article/details/117047152)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值