java小编程练习笔记


import java.io.*;
import java.math.BigInteger;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Scanner;

/**
 * @author lw
 * @createTime 2018/11/14 20:42
 * @description 文件操作
 */
public class WrongFileTest {

    // 创建具有指定路径的文件对象
    @Test
    public void filedome() {
        File file = new File("ddd.txt");
        try {
            if (!file.exists()) {
                file.createNewFile();
            }
        } catch (IOException e) {
            System.out.println("创建失败");
            e.printStackTrace();
        }

        // 创建具有指定路径的文件对象
        // 指定的盘符被占用,不是正常的存储盘符
        File file1 = new File(".\\sds\\jj");
        File txtfile = new File(file1, "atxt.txt");
        file1.mkdirs();
        try {
            txtfile.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    @Test
    public void filedome1() {

        File dirs = new File(".");
        String[] list = dirs.list();
        for (String string : list) {
            System.out.println(string);
        }

        System.out.println("------------------");
        File[] files = dirs.listFiles();
        for (File file : files) {
            System.out.println(file);
        }
        File file1 = new File("a.txt");
        Date d = new Date(file1.lastModified());                //文件的最后修改时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
        System.out.println(sdf.format(d));
    }

    @Test
    public void filedome2() throws Exception {

//        判断E盘目录下是否有后缀名为.jpg的文件,如果有,就输出该文件名称
        File dirs = new File("d:\\");
        //第一种
        File[] subfile = dirs.listFiles();
        for (File files : subfile) {
            if (files.isFile() && files.getName().endsWith(".jbj")) {
                System.out.println(files);
            }
        }
        //第二种
        String[] list = dirs.list();
        for (String string : list) {
            if (string.endsWith("*.jpg")) {
                System.out.println(string);
            }
        }

        //第三种
        String[] arr = dirs.list(new FilenameFilter() {   //内部类实现
            @Override
            public boolean accept(File dir, String name) {
                File file = new File(dir, name);
                return file.isFile() && file.getName().endsWith("*.jpg");
            }
        });
        for (String string : arr) {
            System.out.println(string);
        }

        //使用文件名称过滤器筛选将指定文件夹下的小于200K的小文件获取并打印
        File sudir = new File("c:\\");
        String[] filelength = sudir.list(new FilenameFilter() {
            @Override
            public boolean accept(File dir, String name) {
                File fillen = new File(dir, name);
                return (fillen.length() / 1024 < 200) ? true : false;
            }
        });
        for (String name : filelength) {
            System.out.println(name);
        }

    }

    @Test
    public void filedome3() throws IOException {

        FileInputStream fis = new FileInputStream("a.txt");
        int a;
        byte[] arr = new byte[4];
        while ((a = fis.read(arr)) != -1) {
            System.out.print(new String(arr, 0, a));
        }
        fis.close();

        System.out.println("======================================");
        FileReader fr = new FileReader("a.txt");
        int c;
        while ((c = fr.read()) != -1) {
            System.out.print((char) c);
        }
        fr.close();

    }

    /**
     * @param :args
     * @throws :IOException close方法
     *                      具备刷新的功能,在关闭流之前,就会先刷新一次缓冲区,将缓冲区的字节全都刷新到文件上,再关闭,close方法刷完之后就能写了
     *                      flush方法?
     *                      具备刷新的功能,刷完之后还可以继续写
     */
    @Test
    public void filedome4() throws Exception {
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream("a.txt"));
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("se.txt"));
        byte[] arr = new byte[1024];
        int len;
        while ((len = bis.read()) != -1) {
            bos.write(arr, 0, len);
        }
        bis.close();
        bos.close();
    }

    /**
     * 将键盘录入的数据拷贝到当前项目下的text.txt文件中,键盘录入数据当遇到quit时就退出
     * <p>
     * 分析:
     * 1,创建键盘录入对象
     * 2,创建输出流对象,关联text.txt文件
     * 3,定义无限循环
     * 4,遇到quit退出循环
     * 5,如果不quit,就将内容写出
     * 6,关闭流
     *
     * @throws :IOException
     */
    @Test
    public void filedome5() throws Exception {

        Scanner scanner = new Scanner(System.in);
        FileOutputStream fos = new FileOutputStream("atx.txt");
        while (true) {
            String line = scanner.nextLine();
            if ("qute".equals(line)) {
                break;
            }
            fos.write(line.getBytes());
            fos.write("\t\n".getBytes());
        }
        fos.close();
    }

    @Test
    public void filedome6() {

    }

    @Test
    public void filedome7() throws Exception {
//        FileWriter ss = new FileWriter("ss");
//        ss.write("您好!!!");
//        ss.close();

        BufferedReader bufferedReader = new BufferedReader(new FileReader("a.txt"));
//        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter("a.txt"));
        String lin;
        while ((lin = bufferedReader.readLine()) != null) {
            System.out.println(lin);
        }
        bufferedReader.close();

    }

    //将一个文本文档上的文本反转,第一行和倒数第一行交换,第二行和倒数第二行交换
    @Test
    public void filedome8() throws Exception {
        BufferedReader bufferedReader = new BufferedReader(new FileReader("at.txt"));
        ArrayList<String> list = new ArrayList<>();
        String line;
        while ((line = bufferedReader.readLine()) != null) {
            list.add(line);
        }
        bufferedReader.close();
        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter("cc.txt"));
        for (int i = list.size() - 1; i >= 1; i--) {
            bufferedWriter.write(list.get(i));
            bufferedWriter.newLine();
        }
        bufferedWriter.close();
    }

    //    获取一个文本上每个字符出现的次数,将结果写在times.txt上
    @Test
    public void filedome9() throws Exception {

        BufferedReader bufferedReader = new BufferedReader(new FileReader("a.txt"));
        HashMap<Character, Integer> mp = new HashMap<>();
        int c;
        while ((c = bufferedReader.read()) != -1) {
            char hc = (char) c;
            mp.put(hc, !mp.containsKey(hc) ? 1 : mp.get(hc) + 1);
        }
        bufferedReader.close();
        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter("cdsd"));
        for (Character key : mp.keySet()) {
            bufferedWriter.write(key + "==" + mp.get(key));
        }
        bufferedWriter.close();
    }

    public static int jceng(int num) {
        if (num == 1) {
            return 1;
        } else {
            return num * jceng(num - 1);
        }
    }

    //    获取一个文本上每个字符出现的次数,将结果写在times.txt上
    @Test
    public void filedome10() throws Exception {

        BufferedReader bf = new BufferedReader(new FileReader("ssss"));
        HashMap<Character, Integer> map = new HashMap<>();
        int c;
        while ((c = bf.read()) != -1) {
            char hc = (char) c;
            if (!map.containsKey(hc)) {
                map.put(hc, 1);
            } else {
                map.put(hc, map.get(hc) + 1);
            }
        }
        bf.close();
        BufferedWriter bw = new BufferedWriter(new FileWriter("sw"));
        for (Character key : map.keySet()) {
            bw.write(key + "===" + map.get(key));
        }

        bf.close();
    }

    //    从键盘接收一个文件夹路径,统计该文件夹大小/
    @Test
    public void filedome11() throws Exception {
//        Scanner scanner = new Scanner(System.in);
//        String arr = scanner.nextLine();
        File file = new File("D:\\TOOL\\IDEASpace\\mavedome\\src\\test\\java\\Fu");
        if (!file.exists()) {
            System.out.println("您输入的不是路径");
            System.exit(0);
        }
        int len = 1;
        File[] files = file.listFiles();
        for (File fils : files) {
            len += fils.length();
        }
        System.out.println(len);

    }

    @Test
    public void filedome12() throws Exception {

        BufferedReader br = new BufferedReader(new FileReader("ssd"));
        String line = br.readLine();
        int times = Integer.parseInt(line);
        if (times > 0) {
            //4,在if判断中要将--的结果打印,并将结果通过输出流写到文件上
            System.out.println("您还有" + times-- + "次机会");
            FileWriter fileWriter = new FileWriter("con,txt");
            fileWriter.write(times + " ");
            fileWriter.close();
        } else {
            System.out.println("您的试用次数已到,请购买正版");
        }
        br.close();

    }

    /**
     * 需求:1,从键盘接收一个文件夹路径,统计该文件夹大小
     * <p>
     * 从键盘接收一个文件夹路径
     * 1,创建键盘录入对象
     * 2,定义一个无限循环
     * 3,将键盘录入的结果存储并封装成File对象
     * 4,对File对象判断
     * 5,将文件夹路径对象返回
     * <p>
     * 统计该文件夹大小
     * 1,定义一个求和变量
     * 2,获取该文件夹下所有的文件和文件夹listFiles();
     * 3,遍历数组
     * 4,判断是文件就计算大小并累加
     * 5,判断是文件夹,递归调用
     */
    @Test
    public void filedome13() {

        File file = new File("D:\\TOOL\\IDEASpace\\mavedome\\src\\test");
        System.out.println(getDirlenth(file));
    }

    /**
     * 统计该文件夹大小
     * 1,返回值类型long
     * 2,参数列表File dir
     */
    public static Long getDirlenth(File dir) {

        long length = 0;
        File[] files = dir.listFiles();
        for (File subfiles : files) {
            if (subfiles.isFile()) {
                length += subfiles.length();
            } else {
                length += getDirlenth(subfiles);
            }
        }
        return length;
    }

    /**
     * 删除该文件夹
     * 1,返回值类型 void
     * 2,参数列表File dir
     */
    public static void deleteFile(File dir) {

        File[] subfil = dir.listFiles();
        for (File fils : subfil) {
            if (fils.isFile()) {
                fils.delete();
            } else {
                deleteFile(fils);
            }
        }
        dir.delete();
    }

    /**
     * 从键盘接收一个文件夹路径
     * 1,返回值类型File
     * 2,参数列表无
     */
    public static File getDir() {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入文件路径");
        while (true) {
            String dir = scanner.nextLine();
            File file = new File(dir);
            if (!file.exists()) {
                System.out.println("您录入的文件夹路径不存在,请输入一个文件夹路径");
            } else if (file.isFile()) {
                System.out.println("您录入的是文件路径,请输入一个文件夹路径");
            } else {
                return file;
            }
        }
    }

    /**
     * 需求:3,从键盘接收两个文件夹路径,把其中一个文件夹中
     * (包含内容)拷贝到另一个文件夹中
     * <p>
     * 把其中一个文件夹中(包含内容)拷贝到另一个文件夹中
     * 分析:
     * 1,在目标文件夹中创建原文件夹
     * 2,获取原文件夹中所有的文件和文件夹,存储在File数组中
     * 3,遍历数组
     * 4,如果是文件就用io流读写
     * 5,如果是文件夹就递归调用
     *
     * @throws: IOException
     */
    @Test
    public void filedome14() throws Exception {
        File str = getDir();
        File dest = getDir();
        if (str.equals(dest)) {
            System.out.println("路径一致");
        } else {
            copy(str, dest);
        }

    }

    /*
     * 把其中一个文件夹中(包含内容)拷贝到另一个文件夹中
     * 1,返回值类型void
     * 2,参数列表File src,File dest
     */
    public static void copy(File src, File dest) throws Exception {
        File newdir = new File(dest, src.getName());
        File[] subfiles = newdir.listFiles();
        for (File subfil : subfiles) {
            if (subfil.isFile()) {
                BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(subfil));
                BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(new File(newdir, subfil.getName())));
                int len;
                while ((len = bufferedInputStream.read()) != -1) {
                    bufferedOutputStream.write(len);
                }
                bufferedInputStream.close();
                bufferedOutputStream.close();
            } else {
                copy(subfil, newdir);
            }
        }
    }

    @Test
    public void filedome15() {
//        File file = new File("C:\\Users\\lw\\Desktop\\课件\\day23_code\\讲师代码");
//        printLev(file,0);

        String rootFolderPath = "C:\\Users\\lw\\Desktop\\课件\\day23_code\\讲师代码";
        showTree(0, new File(rootFolderPath));

    }

    public static void printLev(File dir, int lev) {
        //1,把文件夹中的所有文件以及文件夹的名字按层级打印
        File[] files = dir.listFiles();
        for (File file : files) {
            for (int i = 0; i <= lev; i++) {
                System.out.print("\t");
            }
            //3,无论是文件还是文件夹,都需要直接打印
            System.out.println(file.getName());
            if (file.isDirectory()) {
                printLev(file, ++lev);
            }
        }

    }

    public static void showTree(int level, File parentFolderPath) {
        if (parentFolderPath.isDirectory()) {
            File[] childFiles = parentFolderPath.listFiles();
            for (File file : childFiles) {
                showNameByLevel(level);
                System.out.println(file.getName());
                if (file.isDirectory()) {
                    showTree(level + 1, file);
                }
            }
        }
    }

    public static void showNameByLevel(int level) {
        StringBuffer spaceStr = new StringBuffer();
        if (level > 0) {
            for (int i = 0; i < level; i++) {
                spaceStr.append(" ");
            }
        }
        if (spaceStr.length() > 0) System.out.print("|" + spaceStr);
        System.out.println("|");
        if (spaceStr.length() > 0) System.out.print("|" + spaceStr);
        System.out.print("----");
    }

    /**
     * * 不死神兔
     * 故事得从西元1202年说起,话说有一位意大利青年,名叫斐波那契。
     * 在他的一部著作中提出了一个有趣的问题:假设一对刚出生的小兔一个月后就能长成大兔,再过一个月就能生下一对小兔,并且此后每个月都生一对小兔,一年内没有发生死亡,
     * 问:一对刚出生的兔子,一年内繁殖成多少对兔子?
     * 1 1 2 3 5 8 13 21
     * 1 = fun(1)
     * 1 = fun(2)
     * 2 = fun(1) + fun(2)
     * 3 = fun(2) + fun(3)
     */
    @Test
    public void filedome16() {
        System.out.println(fun(8));
    }

    /*
     * 用递归求斐波那契数列
     */
    public static int fun(int num) {
        if (num == 1 || num == 2) {
            return 1;
        } else {
            return fun(num - 2) + fun(num - 1);
        }
    }

    /**
     * @Author:lw
     * @Description: 需求:求出1000的阶乘所有零和尾部零的个数,不用递归做
     * @Date:12:18 2018/11/15
     */
    @Test
    public void filedome17() {
        //求1000的阶乘中所有的零
        BigInteger bi1 = new BigInteger("1");
        for (int i = 1; i <= 1000; i++) {
            BigInteger bi2 = new BigInteger(i + "");
            bi1 = bi1.multiply(bi2); //将bi1与bi2相乘的结果赋值给bi1
        }
        String str = bi1.toString();//获取字符串表现形式
        int count = 0;
        for (int i = 0; i < str.length(); i++) {
            if ('0' == str.charAt(i)) {  //如果字符串中出现了0字符
                count++;
            }
        }
        System.out.println(count);
    }

    @Test
    public void filedome18() {
        //获取1000的阶乘尾部有多少个零
        BigInteger bi1 = new BigInteger("1");
        for (int i = 1; i <= 1000; i++) {
            BigInteger bi2 = new BigInteger(i + "");
            bi1 = bi1.multiply(bi2);
        }
        String str = bi1.toString();
        StringBuffer stringBuffer = new StringBuffer(str);
        str = stringBuffer.reverse().toString(); //链式编程
        int count = 0;
        for (int i = 0; i < str.length(); i++) {
            if ('0' != str.charAt(i)) {
                break;
            } else {
                count++;
            }
        }
        System.out.println(count);
    }

    /**
     * @param :args 需求:求出1000的阶乘尾部零的个数,用递归做
     *              5 10 15 20 25 30 35 40 45 50 55 60 65 70 75 80 85 90 95 100...1000  1000 / 5 = 200
     *              5 * 5   5 * 5 * 2   5 * 5 * 3   5 * 5 * 4   5 * 5 * 5   5 * 5 * 6   200 / 5 = 40
     *              5 * 5 * 5 * 1   5 * 5 * 5 * 2   5 * 5 * 5 * 3   5 * 5 *  5 * 4  5 * 5 *  5 * 5  5 * 5 *  5 * 6  5 * 5 *  5 * 7  5 * 5 *  5 * 8
     *              40 / 5 = 8
     *              5 * 5 * 5 * 5                                                       8 / 5 = 1
     */
    @Test
    public void filedome19() {
        System.out.println(fun1(1000));
    }
    //    需求:求出1000的阶乘尾部零的个数,用递归做
    public static int fun1(int num) {
        if (num > 0 && num < 5) {
            return 0;
        } else {
            return num / 5 + fun1(num / 5);
        }
    }

    /**
     * 获取幸运数字
     * 1,返回值类型int
     * 2,参数列表int num
     */
    @Test
    public void filedome20() {
        System.out.println(getLucklyNum(384));
    }

    /**
     * 获取幸运数字
     * 1,返回值类型int
     * 2,参数列表int num
     */
    public static int getLucklyNum(int num) {
        ArrayList<Integer> list = new ArrayList<>();
        for (int i = 1; i <= num; i++) {
            list.add(i);
        }
        int ncout = 1;                            //用来数数的,只要是3的倍数
        for (int i = 0; list.size() != 1; i++) {   //只要集合中人数超过1
            if (i == list.size()) {           //如果i增长到集合最大的索引+1时
                i = 0;                       //重新归零
            }
            if (ncout % 3 == 0) {
                list.remove(i--);
            }
            ncout++;
        }
        return list.get(0);
    }

猜你喜欢

转载自blog.51cto.com/357712148/2317267
今日推荐