java综合练习——IO流

目录

1.拷贝文件夹

2.加密和解密文件

3.修改文件中的数据

4.修改文本顺序

5.控制软件运行次数

6.制造名字数据

7.制造名字数据(利用hutool包)

8.带权重的随机算法

9.登录注册


1.拷贝文件夹

package IOtest1;

import java.io.*;

public class IODemo {
    public static void main(String[] args) throws IOException {
        File fb = new File("G:\\JavaProgram\\java\\src\\IOtest1\\a");//数据源
        File fe = new File("G:\\JavaProgram\\java\\src\\IOtest1\\copy");//拷贝目的地
        copy(fb, fe);
    }

    private static void copy(File fb, File fe) throws IOException {
        fe.mkdirs();//创建文件夹
        File[] files = fb.listFiles();
        for (File file : files) {
            if (file.isFile()) {
                FileInputStream fis = new FileInputStream(file);
                FileOutputStream fos = new FileOutputStream(new File(fe, file.getName()));//拷贝目标路径(拷贝源同名)
                byte[] bytes = new byte[64];
                int len;
                while ((len = fis.read(bytes)) != -1) {
                    fos.write(bytes, 0, len);
                }
                fos.close();
                fis.close();
            } else {
                copy(file, new File(fe, file.getName()));//文件夹递归拷贝
            }
        }
    }
}

2.加密和解密文件

package IOtest2;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class IODemo {
    public static void main(String[] args) throws IOException {
        FileInputStream fis1 = new FileInputStream("G:\\JavaProgram\\java\\src\\IOtest2\\mellco-1350305367423545345-20210116_125421-img2.jpg");
        FileOutputStream fos1 = new FileOutputStream("G:\\JavaProgram\\java\\src\\IOtest2\\ency.jpg");

        int b1;
        while ((b1 = fis1.read()) != -1) {
            fos1.write(b1 ^ 2);//每个字节都^2进行加密
        }
        fos1.close();
        fis1.close();

        FileInputStream fis2 = new FileInputStream("G:\\JavaProgram\\java\\src\\IOtest2\\ency.jpg");
        FileOutputStream fos2 = new FileOutputStream("G:\\JavaProgram\\java\\src\\IOtest2\\redu.jpg");

        int b2;
        while ((b2 = fis2.read()) != -1) {//每个字节都^2进行解密
            fos2.write(b2 ^ 2);
        }
        fos2.close();
        fis2.close();
    }
}

3.修改文件中的数据

package IOtest3;

import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;

public class IODemo {
    public static void main(String[] args) throws IOException {
        //读取文件
        FileReader fr = new FileReader("G:\\JavaProgram\\java\\src\\IOtest3\\a.txt");
        StringBuilder sb = new StringBuilder();
        int ch;
        while ((ch = fr.read()) != -1) {
            sb.append((char) ch);
        }
        fr.close();
        System.out.println(sb);

        String string = sb.toString();
        String[] split = string.split("-");//切割字符串
        ArrayList list = new ArrayList<>();//切割后放入集合
        for (String str : split) {
            int i = Integer.parseInt(str);
            list.add(i);
        }
        Collections.sort(list);//集合排序
        System.out.println(list);

        //写出文件
        FileWriter fw = new FileWriter("G:\\JavaProgram\\java\\src\\IOtest3\\sort.txt");
        for (int i = 0; i < list.size(); i++) {
            if (i == list.size() - 1) {
                fw.write(list.get(i).toString());
            } else {
                fw.write(list.get(i).toString() + '-');
            }
        }
        fw.close();
    }
}

4.修改文本顺序

package IOtest4;

import java.io.*;
import java.util.*;

public class IODemo {
    public static void main(String[] args) throws IOException {
        //ArrayList实现方式
        BufferedReader br = new BufferedReader(new FileReader("G:\\JavaProgram\\java\\src\\IOtest4\\a.txt"));
        BufferedWriter bw = new BufferedWriter(new FileWriter("G:\\JavaProgram\\java\\src\\IOtest4\\sort.txt"));
        //读取
        String line;
        ArrayList list = new ArrayList<>();
        while ((line = br.readLine()) != null) {
            list.add(line);
        }
        //排序
        Collections.sort(list, new Comparator() {
            @Override
            public int compare(String o1, String o2) {
                int i1 = Integer.parseInt(o1.split("\\.")[0]);
                int i2 = Integer.parseInt(o2.split("\\.")[0]);
                return i1 - i2;
            }
        });
        //写出
        for (String s : list) {
            bw.write(s);
            bw.newLine();
        }
        bw.close();
        br.close();

        //Map实现方式
        BufferedReader br2 = new BufferedReader(new FileReader("G:\\JavaProgram\\java\\src\\IOtest4\\a.txt"));
        BufferedWriter bw2 = new BufferedWriter(new FileWriter("G:\\JavaProgram\\java\\src\\IOtest4\\sort2.txt"));
        //读取,Map无需排序
        String line2;
        TreeMap tm = new TreeMap<>();
        while ((line2 = br2.readLine()) != null) {
            String[] arr = line2.split("\\.");
            tm.put(Integer.parseInt(arr[0]), arr[1]);
        }
        System.out.println(tm);
        //写出
        Set> entries = tm.entrySet();
        for (Map.Entry entry : entries) {
            String value = entry.getValue();
            bw2.write(value);
            bw2.newLine();
        }
        br2.close();
        bw2.close();
    }
}

5.控制软件运行次数

package IOtest5;

import java.io.*;

public class IODemo {
    public static void main(String[] args) throws IOException {
        //读出文本中的次数
        BufferedReader br = new BufferedReader(new FileReader("G:\\JavaProgram\\java\\src\\IOtest5\\a.txt"));
        String line = br.readLine();
        if(line==null)line="0";

        //根据次数执行不同操作
        int count = Integer.parseInt(line);
        count++;
        if (count <= 3) {
            System.out.println("欢迎使用本软件,第" + count + "次使用免费");
        } else {
            System.out.println("本软件只能免费使用3次,欢迎注册会员后继续使用~");
        }
        br.close();
        
        //写出次数
        BufferedWriter bw = new BufferedWriter(new FileWriter("G:\\JavaProgram\\java\\src\\IOtest5\\a.txt"));
        bw.write(count + "");
        bw.close();
    }
}

6.制造名字数据

package IOtest6;

import org.apache.commons.io.input.WindowsLineEndingInputStream;

import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class IODemo {
    public static void main(String[] args) throws IOException {
        //定义变量记录网址
        String familyNameNet = "https://hanyu.baidu.com/shici/detail?pid=0b2f26d4c0ddb3ee693fdb1137ee1b0d&from=kg0";
        String boyNameNet = "http://haoming8.cn/baobao/10881.html";
        String girlNameNet = "http://haoming8.cn/baobao/7641.html";

        //爬取数据(把网络上所有字符拼接)
        String familyNameStr = webCrawler(familyNameNet);
        String boyNameStr = webCrawler(boyNameNet);
        String girlNameStr = webCrawler(girlNameNet);

        //通过正则表达式,把符合要求的数据获取出来
        ArrayList familyNameTempList = getData(familyNameStr, "(.{4})(,|。)", 1);
        System.out.println(familyNameTempList);
        ArrayList boyNameTempList = getData(boyNameStr, "([\\u4E00-\\u9FA5]{2})(、|。)", 1);
        System.out.println(boyNameTempList);
        ArrayList girlNameTempList = getData(girlNameStr, "(.. ){4}..", 0);
        System.out.println(girlNameTempList);

        //处理数据(姓氏)
        ArrayList familyNameList = new ArrayList<>();
        for (String s : familyNameTempList) {
            for (int i = 0; i < s.length(); i++) {
                char c = s.charAt(i);
                familyNameList.add(c + "");
            }
        }
        System.out.println(familyNameList);
        //处理数据(男名)
        ArrayList boyNameList = new ArrayList<>();
        for (String s : boyNameTempList) {
            if (!boyNameList.contains(s))
                boyNameList.add(s);
        }
        System.out.println(boyNameList);
        //处理数据(女名)
        ArrayList girlNameList = new ArrayList<>();
        for (String s : girlNameTempList) {
            String[] arr = s.split(" ");
            for (int i = 0; i < arr.length; i++) {
                girlNameList.add(arr[i]);
            }
        }
        System.out.println(girlNameList);

        //生成数据
        ArrayList list = getInfos(familyNameList, boyNameList, girlNameList, 20, 10);
        System.out.println(list);

        //写出数据
        BufferedWriter bw = new BufferedWriter(new FileWriter("G:\\JavaProgram\\java\\src\\IOtest6\\a.txt"));
        for (String s : list) {
            bw.write(s);
            bw.newLine();
        }
        bw.close();
    }

    private static ArrayList getInfos(ArrayList familyNameList, ArrayList boyNameList, ArrayList girlNameList, int boyCount, int girlCount) {
        //生成男生随机名
        HashSet boyhs = new HashSet<>();
        while (true) {
            if (boyhs.size() == boyCount) break;
            Collections.shuffle(familyNameList);
            Collections.shuffle(boyNameList);
            boyhs.add(familyNameList.get(0) + boyNameList.get(0));
        }
        System.out.println(boyhs);

        //生成女生随机名
        HashSet girlhs = new HashSet<>();
        while (true) {
            if (girlhs.size() == boyCount) break;
            Collections.shuffle(familyNameList);
            Collections.shuffle(girlNameList);
            girlhs.add(familyNameList.get(0) + girlNameList.get(0));
        }
        System.out.println(girlhs);

        //生成完整信息并添加到集合中
        ArrayList list = new ArrayList<>();
        Random r = new Random();
        for (String boy : boyhs) {
            int age = r.nextInt(10) + 18;
            list.add(boy + "-男-" + age);
        }
        for (String girl : girlhs) {
            int age = r.nextInt(8) + 18;
            list.add(girl + "-女-" + age);
        }
        return list;
    }

    public static String webCrawler(String net) throws IOException {
        //正则表达式爬取网站所有字符
        StringBuilder sb = new StringBuilder();
        URL url = new URL(net);
        URLConnection conn = url.openConnection();
        InputStream is = conn.getInputStream();
        InputStreamReader isr = new InputStreamReader(is);

        int ch;
        while ((ch = isr.read()) != -1) {
            sb.append((char) ch);

        }
        isr.close();
        return sb.toString();
    }

    private static ArrayList getData(String str, String regex, int index) {
        ArrayList list = new ArrayList<>();
        //正则表达式筛选目标信息
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(str);
        while (matcher.find()) {
            list.add(matcher.group(index));
        }
        return list;
    }
}

7.制造名字数据(利用hutool包)

package IOtest7;

import java.io.BufferedWriter;
import java.io.FileReader;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ReUtil;
import cn.hutool.http.HttpUtil;
import org.apache.commons.io.FileUtils;

import java.io.FileWriter;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.*;

public class IODemo {
    public static void main(String[] args) throws IOException {
        //定义变量记录网址
        String familyNameNet = "https://hanyu.baidu.com/shici/detail?pid=0b2f26d4c0ddb3ee693fdb1137ee1b0d&from=kg0";
        String boyNameNet = "http://www.haoming8.cn/baobao/10881.html";
        String girlNameNet = "http://www.haoming8.cn/baobao/7641.html";
        //hutool包爬取网站
        String familyNameStr=HttpUtil.get(familyNameNet);
        String boyNameStr=HttpUtil.get(boyNameNet);
        String girlNameStr=HttpUtil.get(girlNameNet);
        //hutool包通过正则表达式筛选
        List familyNameTempList= ReUtil.findAll("(.{4})(,|。)",familyNameStr,1);
        List boyNameTempList=ReUtil.findAll("([\\u4E00-\\u9FA5]{2})(、|。)",boyNameStr,1);
        List girlNameTempList=ReUtil.findAll("(.. ){4}..",girlNameStr,0);

        //处理数据(姓氏)
        ArrayList familyNameList = new ArrayList<>();
        for (String s : familyNameTempList) {
            for (int i = 0; i < s.length(); i++) {
                char c = s.charAt(i);
                familyNameList.add(c + "");
            }
        }
        System.out.println(familyNameList);
        //处理数据(男名)
        ArrayList boyNameList = new ArrayList<>();
        for (String s : boyNameTempList) {
            if (!boyNameList.contains(s))
                boyNameList.add(s);
        }
        System.out.println(boyNameList);
        //处理数据(女名)
        ArrayList girlNameList = new ArrayList<>();
        for (String s : girlNameTempList) {
            String[] arr = s.split(" ");
            for (int i = 0; i < arr.length; i++) {
                girlNameList.add(arr[i]);
            }
        }
        System.out.println(girlNameList);

        //生成数据
        ArrayList list = getInfos(familyNameList, boyNameList, girlNameList, 20, 10);
        System.out.println(list);

        //写出数据
        FileUtil.writeLines(list,"G:\\JavaProgram\\java\\src\\IOtest7\\a.txt", Charset.forName("UTF-8"));
    }

    private static ArrayList getInfos(ArrayList familyNameList, ArrayList boyNameList, ArrayList girlNameList, int boyCount, int girlCount) {
        //生成男生随机名
        HashSet boyhs = new HashSet<>();
        while (true) {
            if (boyhs.size() == boyCount) break;
            Collections.shuffle(familyNameList);
            Collections.shuffle(boyNameList);
            boyhs.add(familyNameList.get(0) + boyNameList.get(0));
        }
        System.out.println(boyhs);

        //生成女生随机名
        HashSet girlhs = new HashSet<>();
        while (true) {
            if (girlhs.size() == boyCount) break;
            Collections.shuffle(familyNameList);
            Collections.shuffle(girlNameList);
            girlhs.add(familyNameList.get(0) + girlNameList.get(0));
        }
        System.out.println(girlhs);

        //生成完整信息并添加到集合中
        ArrayList list = new ArrayList<>();
        Random r = new Random();
        for (String boy : boyhs) {
            int age = r.nextInt(10) + 18;
            list.add(boy + "-男-" + age);
        }
        for (String girl : girlhs) {
            int age = r.nextInt(8) + 18;
            list.add(girl + "-女-" + age);
        }
        return list;
    }
}

8.带权重的随机算法

package IOtest8;

import javax.xml.transform.Result;
import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Random;

public class IODemo {
    public static void main(String[] args) throws IOException {
        //读取数据
        ArrayList list = new ArrayList<>();
        BufferedReader br = new BufferedReader(new FileReader("G:\\JavaProgram\\java\\src\\IOtest8\\a.txt"));
        String line;
        while ((line = br.readLine()) != null) {
            String[] arr = line.split("-");
            Student stu = new Student(arr[0], arr[1], Integer.parseInt(arr[2]), Double.parseDouble(arr[3]));
            list.add(stu);
        }
        br.close();
        //计算总权重
        double weight = 0;
        for (Student student : list) {
            weight = +student.getWeight();
        }
        //计算每个人权重占比
        double[] arr = new double[list.size()];
        int index = 0;
        for (Student student : list) {
            arr[index] = student.getWeight() / weight;
            index++;
        }
        //计算权重范围
        for (int i = 1; i < arr.length; i++) {
            arr[i] = arr[i] + arr[i - 1];
        }
        //随机抽取权重范围
        double num = Math.random();
        int result = -Arrays.binarySearch(arr, num) - 1;
        Student student = list.get(result);
        System.out.println(student);
        //修改权重(减半)
        student.setWeight(student.getWeight() / 2);
        //写入数据
        BufferedWriter bw=new BufferedWriter(new FileWriter("G:\\JavaProgram\\java\\src\\IOtest8\\a.txt"));
        for (Student student1 : list) {
            bw.write(student1.toString());
            bw.newLine();
        }
        bw.close();
    }
}

9.登录注册

package IOtest9;

import javax.naming.Name;
import java.io.*;
import java.util.Scanner;

public class IODemo {
    public static void main(String[] args) throws IOException {
        //读取数据
        BufferedReader br = new BufferedReader(new FileReader("G:\\JavaProgram\\java\\src\\IOtest9\\a.txt"));
        String line = br.readLine();
        br.close();
        //切割数据
        String[] split = line.split("&");
        String[] usernameInfo = split[0].split("=");
        String[] passwordInfo = split[1].split("=");
        String[] countInfo = split[2].split("=");
        String username = usernameInfo[1];
        String password = passwordInfo[1];
        int count = Integer.parseInt(countInfo[1]);
        System.out.println(username);
        System.out.println(password);
        System.out.println(count);
        //用户输入用户名密码
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入用户名");
        String usernameSc = sc.nextLine();
        System.out.println("请输入密码");
        String passwordSc = sc.nextLine();
        //比较输入登录信息和正确登录信息
        if (username.equals(usernameSc) && password.equals(passwordSc) && count < 3) {
            System.out.println("登录成功");
            count = 0;
        } else {
            System.out.println("登录失败");
            count++;
            if (count >= 3) System.out.println("账户被锁定");
        }
        //写出数据
        BufferedWriter bw = new BufferedWriter(new FileWriter("G:\\JavaProgram\\java\\src\\IOtest9\\a.txt"));
        bw.write("username=" + username + "&password=" + password + "&count=" + count);
        bw.close();
    }
}

你可能感兴趣的:(java,开发语言,笔记,学习,idea)