java代码-------IO作业(尚马day23) week5(11)

(1)

/**
 * @author: sunshine
 * @description:  //1. 使用IO技术,创建一个目录,然后复制一个文件到该目录!
 * @data: 2022/3/12  19:10
 * @version: 0.1
 * @since: jdk11
 */
public class Exercise {
    public static void main(String[] args) {
        //将src/a.txt 复制到 exercise/xxx.txt
        File file1 = new File("src/a.txt");   //要复制的文件(源文件)
        File file2 = new File("src/b.txt");   //复制后的文件(目标文件)
        try {
            exercise1(file1, file2);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    private static void exercise1(File sourceFile, File targetFile) throws IOException {

        //高效字符输入流
        BufferedReader reader = new BufferedReader(new FileReader(sourceFile));
        //高效字符输出流
        BufferedWriter writer = new BufferedWriter(new FileWriter(targetFile));

        try (reader; writer) {
            String line;
            while ((line = reader.readLine()) != null) {
                writer.write(line);
                writer.newLine();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

(2)

/**
 * @author: sunshine
 * @description:  //2.使用IO技术,开发出一个控制台的资源管理器!要求:从命令行输入一个路径!
 *   //如果存在,将该目录下所有的文件和文件夹列举出来,如果不存在则输出不存在该路径。
 * @data: 2022/3/12  19:10
 * @version: 0.1
 * @since: jdk11
 */
public class Exercise {
    public static void main(String[] args) {
       String path = "E:\\workspace\\one\\day24";
        File directory = new File(path);
        exercise2(directory, "|-");

    } 

    private static void exercise2(File directory, String s) {
        if (!directory.exists()) {
            System.out.println(directory + "路径不存在  无法查询子级");
            return;
        }
        File[] files = directory.listFiles();
        for (File child : files) {
            System.out.println(s + child.getName());
            if (child.isDirectory()) {
                exercise2(child, "| " + s);
            }
        }
    }

    }

(3)

/**
 * @author: sunshine
 * @description:  //基于转换流,从控制台输入一些字符串,并将该类信息保存到日志文件”log.txt”中去
 * @data: 2022/3/12  19:10
 * @version: 0.1
 * @since: jdk11
 */
public class Exercise {
    public static void main(String[] args) {
       try{
           exercise3();
       }catch(IOException e){
           e.printStackTrace();
       }

    }

    private static void exercise3() throws IOException {
        //读取用户在控制台录入的数据  输入流 read
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));   //in是个InputStream流
        BufferedWriter writer = new BufferedWriter(new FileWriter("src/log.txt"));

        System.out.println("请录入一些数据:");
        try (reader; writer) {                     //释放资源

            while (true) {
                String line = reader.readLine();         //拿到录入的每行内容
                if ("bye".equals(line)) {                //假设最后是bye
                    break;
                }
                writer.write(line);
                writer.newLine();
            }

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

    }

    }

(4)

/**
 * @author: sunshine
 * @description:  //从控制台进行输入用户名以及用户密码,判断是否登录成功!要求准确的用户名和密码存在配置文件中!
 * @data: 2022/3/12  19:10
 * @version: 0.1
 * @since: jdk11
 */
public class Exercise {
    public static void main(String[] args) {
        login();

    }

    private static void login() {

        Scanner input = new Scanner(System.in);
        System.out.println("录入name:");
        String name = input.nextLine();
        System.out.println("录入pass:");
        String pass = input.nextLine();

        //获得配置文件里面的数据
        Properties properties = new Properties();
        try {
            properties.load(new FileInputStream("src/user.properties"));
        } catch (IOException e) {
            e.printStackTrace();
        }

        String username = properties.getProperty("username");
        String password = properties.getProperty("password");
        if (!name.equals(username) || !pass.equals(password)) {
            System.out.println("登录失败");
            input.close();
            return;
        }
        System.out.println("登录成功,欢迎你:" + username);

        input.close();

    }

    }
/**
 * @author: sunshine
 * @description: 4.从控制台进行输入用户名以及用户密码,判断是否登录成功!要求准确的用户名和密码存在配置文件中!
 * @data: 2022/3/12  11:08
 * @version: 0.1
 * @since: jdk11
 */
public class Exercise4 {
    public static void main(String[] args) {
        demo();
    }

    private static void demo() {
        Properties properties = new Properties();
        try {
            //properties.load(new FileInputStream("src/userinfo.properties"));  前期这样写
            //后期这样写
            properties.load(Exercise4.class.getClassLoader().getResourceAsStream("userinfo.properties"));
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println(properties);
    }

}

 

(5)

/**
 * @author: sunshine
 * @description: 5.创建一个学生类,包含属性:学号、姓名、性别,包含show()方法用于显示学生的详细信息。
 *    //创建测试类,在控制台上显示添加学生信息,要求程序循环运行,并依次提示接收学生类的所有属性值,保存到学生对象中,
 *  //再将学生对象保存到集合对象中,并提示“是否继续添加(y/n):”,如果选择“y”则继续添加,否则退出循环,
 *   //并将保存学生数据的集合对象通过序列化保存到“student.dat”文件中。
 *    //实现从“student.dat”文件中反序列化保存学生数据的集合对象,并遍历打印输出学生信息。
 * @data: 2022/3/12  19:10
 * @version: 0.1
 * @since: jdk11
 */
class Student implements Serializable {
    private Integer id;
    private String name;

    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

public class Exercise {
    public static void main(String[] args) {
        try {
            exercise4();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    private static void exercise5() throws IOException, ClassNotFoundException {
        ObjectInput objectInput = new ObjectInputStream(new FileInputStream("src/student.dat"));

        List list = (List) objectInput.readObject();
        list.forEach(System.out::println);
        objectInput.close();
    }

    private static void exercise4() throws IOException {
        Scanner input = new Scanner(System.in);
        int idIndex = 1001;      //id自增,只需录入name
        List studentList = new ArrayList<>(10);

        String s;
        do {
            System.out.println("录入name:");
            String name = input.nextLine();
            Student student = new Student();
            student.setId(idIndex++);
            student.setName(name);
            studentList.add(student);

            System.out.println("是否继续添加学生信息?y/n");
            s = input.nextLine();
        } while (Objects.equals("y", s));

        //将集合对象写入文件中---->序列化  ObjectOutputStream
        ObjectOutput objectOutput = new ObjectOutputStream(new FileOutputStream("src/student.dat"));

        try(objectOutput){
            objectOutput.writeObject(studentList);
            System.out.println("序列化成功");
        }catch (IOException e){
            e.printStackTrace();
        }
    }

    }
/**
 * @author: sunshine
 * @description: 5.创建一个学生类,包含属性:学号、姓名、性别,包含show()方法用于显示学生的详细信息。
 *    //创建测试类,在控制台上显示添加学生信息,要求程序循环运行,并依次提示接收学生类的所有属性值,保存到学生对象中,
 *  //再将学生对象保存到集合对象中,并提示“是否继续添加(y/n):”,如果选择“y”则继续添加,否则退出循环,
 *   //并将保存学生数据的集合对象通过序列化保存到“student.dat”文件中。
 *    //实现从“student.dat”文件中反序列化保存学生数据的集合对象,并遍历打印输出学生信息。
 * @data: 2022/3/12  19:10
 * @version: 0.1
 * @since: jdk11
 */
class Student implements Serializable {

    //要加版本号,上个同理。   这里省略
    private Integer id;
    private String name;

    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

public class Exercise {
    public static void main(String[] args) {
        try {
            exercise4();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    private static void exercise5() throws IOException, ClassNotFoundException {
        ObjectInput objectInput = new ObjectInputStream(new FileInputStream("src/student.dat"));

        Object object;
        while ((object = objectInput.readObject()) != null) {        //readObject() 没有条件进行判断是否读取到末尾  ,故这里没意义
            System.out.println(object);
        }

        //对于序列化而言: 只写一个  以及  只读一次

        //若写入多次  写多个对象  用集合
        //java.io.EOFException 当前线程就会终止
        objectInput.close();
    }

    private static void exercise4() throws IOException {
        Scanner input = new Scanner(System.in);
        int idIndex = 1001;

        ObjectOutput objectOutput = new ObjectOutputStream(new FileOutputStream("src/student.dat"));
        String s;
        do {
            System.out.println("录入name:");
            String name = input.nextLine();
            Student student = new Student();
            student.setId(idIndex++);
            student.setName(name);

            objectOutput.writeObject(student);
            System.out.println("是否继续添加学生信息?y/n");
            s = input.nextLine();
        } while (Objects.equals("y", s));
    }

    }

(6)

/**
 * @author: sunshine
 * @description: 6.已知文件a.txt文件中的内容为“AAbcdea22dferwplkCC321ou1”,
 *   //请编写程序读取该文件内容,要求去掉重复字母(区分大小写字母)并按照自然排序顺序后输出到b.txt文件中。
 *  //即b.txt文件内容应为”123ACabcdefklopruw”这样的顺序输出。
 * @data: 2022/3/12  19:10
 * @version: 0.1
 * @since: jdk11
 */
public class Exercise {
    public static void main(String[] args) {
        try {
            exercise6();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    private static void exercise6() throws IOException {
        //1.读取log.txt文件内容  read  123ACabcdefklopruw  字符输入流 Reader
        List list = new ArrayList<>(10);
        FileReader reader = new FileReader("src/log.txt");

        //2.将读取到的每个字符 存储集合中  List  Set---> TreeSet    Map
        int len;
        while ((len = reader.read()) != -1) {
            list.add(String.valueOf((char) len));
        }
        System.out.println(list);
        list = list.stream().sorted().distinct().collect(Collectors.toList());
        System.out.println(list);
        
        //遍历list集合 将每个字符写入文件中   略
        reader.close();

    }

    }

(7)

/**
 * @author: sunshine
 * @description: //7. 读取任意txt文件内容,并统计出这个文本中每个字符以及每个字符出现的次数,
 *  // 并以以下格式: 字符=次数 持久化保存文件中。
 * @data: 2022/3/12  19:10
 * @version: 0.1
 * @since: jdk11
 */
public class Exercise {
    public static void main(String[] args) {
        try {
            exercise7();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void exercise7() throws IOException {

        //Map ---> Properties.store()  将内容直接存到文件里
        Properties properties = new Properties();
        FileReader reader = new FileReader("src/log.txt");
        int len;
        while ((len = reader.read()) != -1) {
            String key = String.valueOf((char) len);
            String countStr = properties.getProperty(key);
            if (countStr == null) {
                countStr = "1";
            } else {
                countStr = String.valueOf(Integer.parseInt(countStr) + 1);
            }
            properties.setProperty(key, countStr);
        }
        properties.store(new FileOutputStream("src/b.txt"), "");
        reader.close();
    }

    }

(8)

/**
 * @author: sunshine
 * @description: //8. 使用集合相关的功能,存储10个1-50(含50)的随机偶数元素,要求数字不能重复,
 *    // 添加完成后从大到小倒序遍历输出到控制台并使用IO流将集合中的元素按指定格式输出到当指定文件中,
 *   // 例如: 48,44,40,38,34,30,26……
 * @data: 2022/3/12  19:10
 * @version: 0.1
 * @since: jdk11
 */
public class Exercise {
    public static void main(String[] args) {
        try {
            exercise8();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void exercise8() throws IOException {

        ThreadLocalRandom random = ThreadLocalRandom.current();       //获得一个随机数对象
        List list = new ArrayList<>(10);
        for (int i = 0; i < 10; i++) {
            int num = random.nextInt(1, 51);
            if (num % 2 == 0) {
                list.add(num);
            } else {
                i--;
            }
        }
        list.sort(Comparator.comparing(Integer::intValue).reversed());
        FileWriter writer = new FileWriter("src/b.txt");
        for (Integer num : list) {
            writer.write(num.toString());
            writer.write(",");           //最后会多个逗号
        }
        writer.close();


        //List integers = random.ints(10, 1, 51).boxed().collect(Collectors.toList());   若啥都不管,只随机10个
    }

    }

(9)

public class StudentInfo {

    private String name;
    private Integer age;
    private Integer score;

    @Override
    public String toString() {
        return "StudentInfo{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", score=" + score +
                '}';
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public Integer getScore() {
        return score;
    }

    public void setScore(Integer score) {
        this.score = score;
    }
}
/**
 * @author: sunshine
 * @description: 9.已知student_info.txt文件中有如下数据:(姓名-年龄-总分)
 *                 张三-21-98
 *                 李四-23-97
 *                 王五-25-100
 *                 赵六-15-100
 *                 孙七-19-93
 * 运用IO技术获取将该文件中的数据分别封装成5个Student(姓名为String类型,年龄为int类型,总分为int类型 )对象存入集合中(需要自己定义Student类)
 * 要求:根据学生的总分进行排序(降序),如果分数相同则比较年龄,年龄较大的排在前面。并显示排序之后的结果。
 * @data: 2022/3/12  19:10
 * @version: 0.1
 * @since: jdk11
 */
public class Exercise {
    public static void main(String[] args) {
        try {
            exercise9();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void exercise9() throws IOException {
        //5个Student(姓名为String类型,年龄为int类型,总分为int类型 )对象存入集合中
        BufferedReader reader = new BufferedReader(new FileReader("src/b.txt"));
        String info;
        List list = new ArrayList<>(10);
        while ((info = reader.readLine()) != null) {
            String[] array = info.split("-");
            StudentInfo studentInfo = new StudentInfo();
            studentInfo.setName(array[0]);
            studentInfo.setAge(Integer.parseInt(array[1]));
            studentInfo.setScore(Integer.parseInt(array[2]));
            list.add(studentInfo);
        }
        //根据学生的总分进行排序(降序)
        list.sort(Comparator.comparing(StudentInfo::getScore).reversed().thenComparing(StudentInfo::getAge));
        list.forEach(System.out::println);

    }

    }

你可能感兴趣的:(尚马Java代码,java,开发语言)