1. 程式人生 > >java小程式設計練習筆記

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);
    }