Java学习记录(五):集合进阶、Stream流、方法引用、文件和IO、多线程以及网络编程
1、集合进阶练习
(1)利用集合以及Random类实现随机点名
import java.util.ArrayList;
import java.util.Collections;
import java.util.Random;
public class RandomSelect {
public static void main(String[] args) {
String[] strs = {"Ning", "Zhang", "Xie", "Liu", "Li", "Zhou"};
ArrayList<String> list = new ArrayList<>();
Collections.addAll(list, strs);
Random rand = new Random();
int index = rand.nextInt(list.size());
String name = list.get(index);
System.out.println(name);
System.out.println("------------------");
Collections.shuffle(list);
System.out.println(list.get(0));
}
}
(2)在第(1)问的基础上实现以70%的概率随机到男生,以30%的概率随机到女生
import java.util.ArrayList;
import java.util.Collections;
import java.util.Random;
public class RandomSelect2 {
public static void main(String[] args) {
Random rand = new Random();
ArrayList<Integer> rList = new ArrayList<>();
Collections.addAll(rList, 1,1,1,1,1,1,1);
Collections.addAll(rList, 0,0,0);
int bog = rand.nextInt(rList.size());
int base = rList.get(bog);
ArrayList<String> boyList = new ArrayList<>();
ArrayList<String> girlList = new ArrayList<>();
Collections.addAll(boyList, "Zhang", "Li", "Wang");
Collections.addAll(girlList, "Liu", "Ling", "Zhou", "Dai");
if (base == 1){
int index = rand.nextInt(boyList.size());
System.out.println(boyList.get(index));
} else if (base == 0){
int index = rand.nextInt(girlList.size());
System.out.println(girlList.get(index));
}
}
}
(3)进行随机点名,但是要求已经点到过的名字不能再被点到
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Random;
public class RandomSelect3 {
public static void main(String[] args) {
ArrayList<String> nameList = new ArrayList<>();
Collections.addAll(nameList, "1", "2", "3", "4", "5", "6", "7", "8", "9");
HashMap<String, Boolean> hashMap = new HashMap<>();
Random rand = new Random();
while (hashMap.size() != nameList.size()){
String name = "";
do {
int randomIndex = rand.nextInt(nameList.size());
name = nameList.get(randomIndex);
} while(hashMap.containsKey(name));
System.out.println(name);
hashMap.put(name, true);
}
}
}
(4)利用列表或集合实现斗地主控制台版的洗牌、发牌等操作
import java.util.*;
public class PokerGame {
static ArrayList<String> pokers;
static HashMap<String, Integer> pokersMap;
static {
// 准备牌
pokers = new ArrayList<>();
pokersMap = new HashMap<>();
String[] colors = {"♣", "♥", "♠", "♦"};
String[] numbers = {"3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A", "2"};
for (int i = 0; i < numbers.length; i++) {
for (int j = 0; j < colors.length; j++) {
pokers.add(colors[j] + numbers[i]);
}
}
pokers.add("bJoker");
pokers.add("sJoker");
pokersMap.put("J", 11);
pokersMap.put("Q", 12);
pokersMap.put("K", 13);
pokersMap.put("A", 14);
pokersMap.put("2", 15);
pokersMap.put("sJoker", 16);
pokersMap.put("bJoker", 17);
}
PokerGame() {
// 准备牌
//System.out.println(pokers);
// 洗牌
System.out.println("-------------------------");
Collections.shuffle(pokers);
System.out.println(pokers);
// 发牌
System.out.println("------------------------------");
ArrayList<String> lord = new ArrayList<>();
ArrayList<String> player1 = new ArrayList<>();
ArrayList<String> player2 = new ArrayList<>();
ArrayList<String> player3 = new ArrayList<>();
for (int i = 0; i < pokers.size(); i++) {
if (i <= 2) {
lord.add(pokers.get(i));
continue;
}
if (i % 3 == 0){
player1.add(pokers.get(i));
} else if (i % 3 == 1){
player2.add(pokers.get(i));
} else {
player3.add(pokers.get(i));
}
}
//排序
orderPokers(lord);
orderPokers(player1);
orderPokers(player2);
orderPokers(player3);
// 看牌
lookPokers("底牌", lord);
lookPokers("玩家1", player1);
lookPokers("玩家2", player2);
lookPokers("玩家3", player3);
}
public void lookPokers(String name, ArrayList<String> player) {
StringJoiner sj = new StringJoiner(",", "", "");
for (String s : player) {
sj.add(s);
}
System.out.println(name + ": " + sj.toString());
}
public void orderPokers(ArrayList<String> pokers) {
Collections.sort(pokers, new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
String color1 = o1.substring(0, 1);
int value1 = getValue(o1);
String color2 = o2.substring(0, 1);
int value2 = getValue(o2);
int i = value1 - value2;
return i == 0 ? color1.compareTo(color2) : i;
}
});
}
public int getValue(String poker) {
String number = "";
if (poker.equals("bJoker") || poker.equals("sJoker")) {
number = poker;
} else {
number = poker.substring(1);
}
if (pokersMap.containsKey(number)) {
return pokersMap.get(number);
} else {
return Integer.parseInt(number);
}
}
}
2、字典测试(Map双列集合)
(1)利用HashMap存储自定义集合,这里自定义一个Student的Java bean类,创建一个HashMap进行存储。
// Student Java bean
// 在当Map集合的键为自定义数据类型时,通常需要重写equals、hashCode以及compareTo方法
public class Student implements Comparable<Student>{
private String name;
private int age;
public Student() {
}
public Student(String name, int age) {
this.name = name;
this.age = age;
}
/**
* 获取
* @return name
*/
public String getName() {
return name;
}
/**
* 设置
* @param name
*/
public void setName(String name) {
this.name = name;
}
/**
* 获取
* @return age
*/
public int getAge() {
return age;
}
/**
* 设置
* @param age
*/
public void setAge(int age) {
this.age = age;
}
public String toString() {
return "Student{name = " + name + ", age = " + age + "}";
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || this.getClass() != obj.getClass()) return false;
Student student = (Student) obj;
return name.equals(student.name) && age == student.age;
}
@Override
public int hashCode() {
return this.name.hashCode() + this.age;
}
@Override
public int compareTo(Student o) {
if (this.age != o.age) {
return this.age - o.age;
}
else {
char s1 = this.name.charAt(0);
char s2 = o.name.charAt(0);
return s1 - s2;
}
}
}
// 创建HashMap对象并进行存储遍历
import java.util.HashMap;
public class HashMapTest1 {
public static void main(String[] args) {
HashMap<Student, String> hashMap = new HashMap<>();
hashMap.put(new Student("刘", 21), "重庆");
hashMap.put(new Student("关", 22), "成都");
hashMap.put(new Student("张", 21), "荆州");
hashMap.forEach((key, value) -> {
System.out.println(key.getName() + " " + key.getAge() + " " + value);
});
System.out.println("----------------------------");
hashMap.put(new Student( "张", 21), "北京");
hashMap.forEach((key, value) -> {
System.out.println(key.getName() + " " + key.getAge() + " " + value);
});
System.out.println("----------------------------");
hashMap.put(new Student("张", 25), "北京");
hashMap.forEach((key, value) -> {
System.out.println(key.getName() + " " + key.getAge() + " " + value);
});
}
}
(2)假设班上有80名学生,准备了A、B、C、D四个景点供学生自由选择进行秋游活动,每一个学生最多只能选择一个景点,请统计出各个景点分别有多少学生数。
import java.util.HashMap;
import java.util.Random;
public class HashMapTest2 {
public static void main(String[] args) {
int counter = 0;
Random random = new Random();
String[] scenery = {"A", "B", "C", "D"};
HashMap<Student, String> hashMap = new HashMap<>();
while (counter < 80) {
int idx = random.nextInt(scenery.length);
hashMap.put(new Student("" + counter, counter), scenery[idx]);
counter++;
}
HashMap<String, Integer> counterMap = new HashMap<>();
hashMap.forEach((key, value) -> {
if (counterMap.containsKey(value)) {
counterMap.put(value, counterMap.get(value) + 1);
} else {
counterMap.put(value, 1);
}
});
counterMap.forEach((key, value) -> {
System.out.println(key + ": " + value);
});
}
}
(3)通过Map的keySet集合遍历字典
import java.util.HashMap;
import java.util.Iterator;
public class MapTraversal1 {
public static void main(String[] args) {
HashMap<String, String> hashMap = new HashMap<>();
hashMap.put("a", "b");
hashMap.put("c", "d");
hashMap.put("e", "f");
// 遍历方法1
// hashMap.forEach((key, value) -> {
// System.out.println(key + "=" + value);
// });
hashMap.keySet().forEach(s -> System.out.println("key: " + s + " value: " + hashMap.get(s)));
System.out.println("--------------------------");
// 遍历方法2
for (String key : hashMap.keySet()) {
System.out.println(key + "=" + hashMap.get(key));
}
System.out.println("-----------------------------");
// 遍历方法3
Iterator<String> iterator = hashMap.keySet().iterator();
while (iterator.hasNext()) {
String key = iterator.next();
System.out.println(key + "=" + hashMap.get(key));
}
}
}
(4)通过Map的entrySet集合遍历整个字典
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
public class MapTraversal2 {
public static void main(String[] args) {
HashMap<String, String> hashMap = new HashMap<>();
hashMap.put("a", "b");
hashMap.put("c", "d");
hashMap.put("e", "f");
Set<Map.Entry<String, String>> entrySet = hashMap.entrySet();
// 遍历方法1
entrySet.forEach(entry -> System.out.println(entry.getKey() + "=" + entry.getValue()));
System.out.println("--------------------------");
// 遍历方法2
for (Map.Entry<String, String> entry : entrySet) {
System.out.println(entry.getKey() + "=" + entry.getValue());
}
System.out.println("-----------------------------");
// 遍历方法3
Iterator<Map.Entry<String, String>> iterator = entrySet.iterator();
while (iterator.hasNext()) {
Map.Entry<String, String> entry = iterator.next();
System.out.println(entry.getKey() + "=" + entry.getValue());
}
}
}
(5)TreeMap:主要用于存储需要按照键进行排序的数据,默认按照数字或字母的编码升序进行排列,或者可以在创建对象时自定义排序规则。
import java.util.Comparator;
import java.util.TreeMap;
public class TreeMapTest {
public static void main(String[] args) {
/*
// 自定义键排序规则一,重写接口中第二个参数表示Map中已有键,第一个参数表示待添加键,返回值若为正数就将待添加键放置于当前已有键的后面,若为
// 负数就放置于当前键的前面,依次和Map中前面所有已有键进行比较,直到找到存放位置
// 正常重写比较方法
TreeMap<Integer, String> tm = new TreeMap<>(new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o1 - o2;
}
});
// lambda表达式,升序缩写
TreeMap<Integer, String> tm = new TreeMap<>((o1, o2) -> o1 - o2);
// lambda表达式,降序缩写
TreeMap<Integer, String> tm = new TreeMap<>((o1, o2) -> o1 - o2);
*/
TreeMap<Integer, String> tm = new TreeMap<>();
tm.put(2, "two");
tm.put(1, "one");
tm.put(3, "three");
tm.forEach((k, v) -> System.out.println(k + " : " + v));
}
}
(6)当TreeMap的键为引用数据类型时,比如前面第(1)点创建的学生类,那么就需要在类中重写compareTo方法,用于重新制定排序规则
public class TreeMapTest2 {
public static void main(String[] args) {
TreeMap<Student, String> tm = new TreeMap<>();
tm.put(new Student("ciiii", 12), "Chongqing");
tm.put(new Student("aiiii", 15), "Beijing");
tm.put(new Student("biiii", 13), "Shanghai");
tm.put(new Student("biiii", 12), "Tianjing");
tm.forEach((k,v) -> System.out.println(k + "\t" + v));
}
}
(7)利用TreeMap统计字符串中的各个字母个数
import java.util.TreeMap;
public class LetterCounter {
public static void main(String[] args) {
String str = "aababcabcdabcde";
TreeMap<Character, Integer> tMap = new TreeMap<>();
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (tMap.containsKey(c)) {
tMap.put(c, tMap.get(c) + 1);
} else {
tMap.put(c, 1);
}
}
System.out.println(tMap);
}
}
(8)HashMap嵌套
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
public class NestedMap {
public static void main(String[] args) {
HashMap<String, HashSet<String>> hashMap = new HashMap<>();
HashSet<String> set1 = new HashSet<>();
Collections.addAll(set1, "南京市", "扬州市", "苏州市", "无锡市", "常州市");
HashSet<String> set2 = new HashSet<>();
Collections.addAll(set2, "武汉市", "孝感市", "十堰市", "宜昌市", "鄂州市");
HashSet<String> set3 = new HashSet<>();
Collections.addAll(set3, "石家庄市", "唐山市", "邢台市", "保定市", "张家口市");
hashMap.put("江苏省", set1);
hashMap.put("湖北省", set2);
hashMap.put("河北省", set3);
System.out.println(hashMap);
}
}
3、Collections工具类
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
public class CollectionsTest {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
Collections.addAll(list, "a", "b", "c", "d", "e");
System.out.println(list);
System.out.println("--------------------");
Collections.shuffle(list);
System.out.println(list);
System.out.println("------------------------");
Collections.reverse(list);
System.out.println(list);
// System.out.println("-----------------------");
// Collections.sort(list);
// System.out.println(list);
System.out.println("------------------------");
Collections.sort(list, (o1, o2) -> o2.compareTo(o1));
System.out.println(list);
System.out.println("---------------------------");
Collections.fill(list, "ccc");
System.out.println(list);
System.out.println("---------------------------");
list.clear();
Collections.addAll(list, "d", "g", "a", "c", "x", "f");
System.out.println(list);
System.out.println("-------------------------");
String max = Collections.max(list);
System.out.println(max);
System.out.println("---------------------------");
String min = Collections.min(list);
System.out.println(min);
System.out.println("---------------------------");
Collections.swap(list, 0, 3);
System.out.println(list);
System.out.println("---------------------------");
ArrayList<String> list2 = new ArrayList<>();
Collections.addAll(list2, "a", "b", "c", "d", "e", "f");
Collections.copy(list2, list);
System.out.println(list2);
System.out.println("--------------------------");
Collections.sort(list2);
int idx = Collections.binarySearch(list2, "g");
System.out.println(idx + ": " + list2.get(idx));
}
}
4、Stream流
(1)将1-10共10个数存放于列表当中,请使用filter过滤掉奇数,只保留偶数,最后使用一个集合把他收集起来
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
public class StreamTest1 {
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<>();
Collections.addAll(list, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
Integer[] even = list.stream().filter(i -> i % 2 == 0).toArray(value -> new Integer[value]);
System.out.println(Arrays.toString(even));
}
}
(2)将一个列表元素类型为字符串,且存储有如“LiHua,23”将姓名和年龄按“,”分隔的列表,筛选出其中年龄小于24岁的那一部分,同时将其映射为Map双列集合。
import java.util.ArrayList;
import java.util.Map;
import java.util.stream.Collectors;
public class StreamTest2 {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
list.add("zhangsan, 23");
list.add("lisi, 24");
list.add("wangwu, 25");
Map<String, Integer> map = list.stream()
.filter(s -> Integer.parseInt(s.split(", ")[1]) >= 24)
.collect(Collectors.toMap(s -> s.split(", ")[0], s -> Integer.parseInt(s.split(", ")[1])));
map.forEach((k, v) -> System.out.println(k + ": " + v));
}
}
(3)现在有两个数组列表集合,第一个集合中:存储6名男演员的名字和年龄。第二个集合中:存储6名女演员的名字和年龄。姓名和年龄中间用逗号隔开。比如:张三,23第一个集合中:存储6名男演员的名字和年龄。第二个集合中:存储6名女演员的名字和年龄。姓名和年龄中间用逗号隔开.比如:张三,23岁。要求完成如下的操作:要求完成如下的操作:1、男演员只要名字为3个字的前两人;2、女演员只要姓杨的,并且不要第一个;3、把过滤后的男演员姓名和女演员姓名合并到一起;4、将上一步的演员信息封装成Actor对象;5、将所有的演员对象都保存到List集合中;备注:演员类演员,属性只有一个:姓名,年龄。
import stream.bean.Actor;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class StreamTest3 {
public static void main(String[] args) {
ArrayList<String> actorList = new ArrayList<>();
ArrayList<String> actressList = new ArrayList<>();
Collections.addAll(actorList, "张张张,24", "李李李,23", "周周,21", "刘刘刘,26", "王王,22", "曾曾曾,23");
Collections.addAll(actressList, "商商,24", "刘刘,23", "杨黄黄,21", "杨杨杨,26", "王王王,22", "杨杨,23");
Stream<String> stream1 = actorList.stream()
.filter(s -> 3 == s.split(",")[0].length())
.limit(2);
Stream<String> stream2 = actressList.stream()
.filter(s -> s.startsWith("杨"))
.skip(1);
List<Actor> actors = Stream
.concat(stream1, stream2)
.map(actor -> new Actor(actor.split(",")[0], Integer.parseInt(actor.split(",")[1])))
.toList();
for (Actor actor : actors) {
System.out.println(actor);
}
}
}
5、函数引用,其实就是在lambda表达式的基础上,使用当前已有的函数替换那个lambda,要求该函数是已经存在的、参数与返回值与抽象函数一致以及函数功能与当前需求一致。
(1)使用类的构造函数来当做函数引用,同时也实现了数组的函数引用方式
public class StreamTest4 {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
Collections.addAll(list, "Zhangsan,23", "Lisi,25", "Wangwu,22");
/*Student[] students = list.stream().map(new Function<String, Student>() {
@Override
public Student apply(String s) {
return new Student(s.split(",")[0], Integer.parseInt(s.split(",")[1]));
}
}).toArray(new IntFunction<Student[]>() {
@Override
public Student[] apply(int value) {
return new Student[value];
}
});*/
/*Student[] students = list.stream()
.map(s -> new Student(s.split(",")[0], Integer.parseInt(s.split(",")[1])))
.toArray(value -> new Student[value]);*/
Student[] students = list.stream()
.map(Student::new) // 当前引用表示使用Student的构造函数来充当引用方法
.toArray(Student[]::new); // 这里表示以Student为数据类型的列表
for (Student student : students) {
System.out.println(student);
}
}
}
(2)列表格式如4.(3)中一致,要求只输出的名字
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
public class StreamTest7 {
public static void main(String[] args) {
ArrayList<Student> students = new ArrayList<>();
Collections.addAll(students, new Student("zhangsan,25"), new Student("lisi,25"), new Student("wangwu,25"));
String[] strings = students.stream().map(Student::getName).toArray(String[]::new);
System.out.println(Arrays.toString(strings));
}
}
(3)列表格式如4.(3)中一致,要求改为以“-”符号进行链接并转换成列表输出。
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
public class StreamTest6 {
public static void main(String[] args) {
ArrayList<Student> students = new ArrayList<>();
Collections.addAll(students, new Student("zhangsan,25"), new Student("lisi,25"), new Student("wangwu,25"));
String[] strings = students.stream().map(StreamTest6::func1).toArray(String[]::new);
System.out.println(Arrays.toString(strings));
}
public static String func1(Student student) {
return student.getName() + "-" + student.getAge();
}
}
6、异常捕捉机制之自定义异常
首先定义一个Java bean类,如下,同时在设置姓名和年龄的时候需要抛出对应异常
public class Girl {
private String name;
private int age;
public Girl() {
}
public Girl(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
if (name.length() < 3 || name.length() > 10) {
throw new NameFormatException(name + " must be between 3 and 10 characters");
}
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
if (age < 18 || age > 30) {
throw new AgeOutOfBoundsException("Age must be between 18 and 30");
}
this.age = age;
}
@Override
public String toString() {
return "Girl{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
其次,自定义一个类继承运行时异常(RuntimeException)命名为NameFormatException用于处理姓名格式错误
public class NameFormatException extends RuntimeException{
public NameFormatException() {
}
public NameFormatException(String message) {
super(message);
}
}
然后再自定义一个类继承运行时异常,命名为AgeOutOfBoundsException用于处理年龄超出范围错误
public class AgeOutOfBoundsException extends RuntimeException {
public AgeOutOfBoundsException() {
}
public AgeOutOfBoundsException(String message) {
super(message);
}
}
最后,编写一个启动类,让其输入姓名和年龄,并进行异常捕捉
import java.util.Scanner;
public class DataFromKeyboard {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Girl girl = new Girl();
while (true) {
try {
System.out.println("Enter name: ");
String name = sc.nextLine();
girl.setName(name);
System.out.println("Enter age: ");
String age = sc.nextLine();
girl.setAge(Integer.parseInt(age));
break;
} catch (NameFormatException | NumberFormatException | AgeOutOfBoundsException e) {
e.printStackTrace();
}
}
System.out.println(girl);
}
}
7、File文件操作类
(1)获取一个本地文件的最后一次修改时间,并以yyyy年MM月dd日 HH:mm:ss格式进行输出
import java.io.File;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
public class FileTest1 {
public static void main(String[] args) {
File file = new File("D:\\Document\\IDEA\\JavaReview\\src\\main\\java\\api\\Algorithm1.java");
long lastModifiedTime = file.lastModified();
Date date = new Date(lastModifiedTime);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
System.out.println(simpleDateFormat.format(date));
}
}
(2)创建一个文件夹,并在该文件夹下创建一个txt文件
import java.io.File;
import java.io.IOException;
public class FileTest2 {
public static void main(String[] args) throws IOException {
File file = new File("aaa");
boolean newFile = file.mkdir();
System.out.println(newFile);
boolean flag = new File("aaa\\a.txt").createNewFile();
System.out.println(flag);
}
}
(3)寻找某一个文件夹下所有的.avi格式文件
import java.io.File;
public class FileTest3 {
public static void main(String[] args) {
File file = new File("aaa");
String[] files = file.list();
assert files != null;
for (String s : files) {
File file1 = new File(file, s);
if (file1.isFile() && file1.getName().endsWith(".avi")) {
System.out.println(file1);
}
}
}
}
(4)寻找某一个文件夹下所有的.avi格式文件,同时若当前文件夹还包含子文件夹,还需将所有子文件夹的对应都找出来。这里使用递归实现
import java.io.File;
public class FileTest4 {
public static void main(String[] args) {
File dir = new File("aaa");
listFileAndDir(dir);
}
public static void listFileAndDir(File dir) {
if (dir.isDirectory()) {
String[] files = dir.list();
assert files != null;
for (String file : files) {
File file1 = new File(dir, file);
if (file1.isFile() && file1.getName().endsWith(".avi")) {
System.out.println(file1.getPath());
} else {
listFileAndDir(file1);
}
}
}
}
}
(5)删除某一个目录下的所有文件以及文件夹,仍然采用递归实现
import java.io.File;
public class FileTest5 {
public static void main(String[] args) {
File dir = new File("aaa\\bbb");
deleteDirs(dir);
}
public static void deleteDirs(File dir) {
String[] files = dir.list();
assert files != null;
if (files.length == 0) {
boolean delete = dir.delete();
if (delete){
System.out.println("Deleted " + dir);
}
} else {
for (String file : files) {
File file1 = new File(dir, file);
if (file1.isFile()) {
boolean delete = file1.delete();
if (delete){
System.out.println("Deleted " + file1);
}
} else {
deleteDirs(file1);
}
}
}
boolean delete = dir.delete();
if (delete){
System.out.println("Deleted " + dir);
}
}
}
(6)利用Map进行计数,统计某一个目录下所有的类型文件对应的总数
import java.io.File;
import java.util.HashMap;
public class FileTest6 {
public static void main(String[] args) {
File dir = new File("aaa");
HashMap<String, Integer> counterMap = getFileCounts(dir);
counterMap.forEach((k, v) -> System.out.println(k + ": " + v + "个"));
}
public static HashMap<String, Integer> getFileCounts(File dir) {
HashMap<String, Integer> counterMap = new HashMap<>();
String[] files = dir.list();
assert files != null;
for (String file : files) {
File file1 = new File(dir, file);
if (file1.isFile()) {
if (file1.getName().endsWith(".txt")) {
if (!counterMap.containsKey(".txt")){
counterMap.put(".txt", 1);
} else {
counterMap.put(".txt", counterMap.get(".txt") + 1);
}
} else if (file1.getName().endsWith(".avi")) {
if (!counterMap.containsKey(".avi")){
counterMap.put(".avi", 1);
} else {
counterMap.put(".avi", counterMap.get(".avi") + 1);
}
} else if (file1.getName().endsWith(".doc")) {
if (!counterMap.containsKey(".doc")){
counterMap.put(".doc", 1);
} else {
counterMap.put(".doc", counterMap.get(".doc") + 1);
}
}
} else {
HashMap<String, Integer> tempMap = getFileCounts(file1);
for (String key : tempMap.keySet()) {
int value = tempMap.get(key);
if (counterMap.containsKey(key)) {
counterMap.put(key, counterMap.get(key) + value);
} else {
counterMap.put(key, value);
}
}
}
}
return counterMap;
}
}
(7)统计某一个目录的整体大小
import java.io.File;
import java.util.HashMap;
public class FileTest7 {
public static void main(String[] args) {
File dir = new File("aaa");
long len = getFileCounts(dir);
System.out.println("length: " + len);
}
public static long getFileCounts(File dir) {
long len = 0;
String[] files = dir.list();
assert files != null;
for (String file : files) {
File file1 = new File(dir, file);
if (file1.isFile()) {
len += file1.length();
} else {
len += getFileCounts(file1);
}
}
return len;
}
}
8、IO流
(1)利用IO流将一个目录拷贝到另一个目录下,要求所有的文件都拷贝
import java.io.*;
public class IOTest1 {
public static void main(String[] args) throws IOException {
File src = new File("aaa");
File dest = new File("dest");
copyDir(src, dest);
}
public static void copyDir(File src, File dest) throws IOException {
dest.mkdir();
File[] files = src.listFiles();
assert files != null;
for (File file : files) {
if (file.isFile()){
FileInputStream fis = new FileInputStream(file);
FileOutputStream fos = new FileOutputStream(new File(dest, file.getName()));
byte[] buf = new byte[1024];
int len;
while ((len = fis.read(buf)) != -1){
fos.write(buf, 0, len);
}
fos.close();
fis.close();
} else {
copyDir(file, new File(dest, file.getName()));
}
}
}
}
(2)对某一个文件进行加密
import java.io.*;
public class IOTest2 {
public static void main(String[] args) throws IOException {
encryption("Atest\\Li.jpg", "Atest\\encryption.jpg");
encryption("Atest\\encryption.jpg", "Atest\\decryption.jpg");
}
public static void encryption(String src, String dest) throws IOException {
FileInputStream fis = new FileInputStream(src);
FileOutputStream fos = new FileOutputStream(dest);
int b;
while ((b = fis.read()) != -1){
fos.write(b ^ 15);
}
fos.close();
fis.close();
}
public static void decryption(String src, String dest) throws IOException {
FileInputStream fis = new FileInputStream(src);
FileOutputStream fos = new FileOutputStream(dest);
int b;
while ((b = fis.read()) != -1){
fos.write(b ^ 15);
}
fos.close();
fis.close();
}
}
(3)一个txt文件中存在一行内容4-5-2-1-3-6,请使用IO流读取后进行排序,然后再写出到文件
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Arrays;
import java.util.StringJoiner;
public class IOTest3 {
public static void main(String[] args) throws IOException {
FileReader fr = new FileReader("Atest\\a.txt");
FileWriter fw = new FileWriter("Atest\\a_sorted.txt");
StringBuilder sb = new StringBuilder();
int i;
while ((i = fr.read()) != -1) {
sb.append((char) i);
}
System.out.println(sb);
System.out.println("=========================");
Integer[] arr = Arrays.stream(sb.toString().split("-"))
.map(Integer::parseInt)
.sorted()
.toArray(Integer[]::new);
StringJoiner sj = new StringJoiner("-", "", "");
for (int j : arr) {
sj.add(j+"");
}
System.out.println(sj);
fw.write(sj.toString());
fw.flush();
fw.close();
fr.close();
}
}
(4)请使用IO流实现用户登录错误次数统计,若超过3次将锁定该账号
import java.io.*;
public class IOTest4 {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new FileReader("Atest\\count.txt"));
String line = br.readLine();
int count = Integer.parseInt(line);
br.close();
count++;
if (count > 3) {
System.out.println("只能免费使用3次,若要继续使用欢迎开通SVIP!");
} else {
System.out.println("欢迎试用本软件,剩余"+ (3 - count) +"次免费使用机会!");
}
BufferedWriter bw = new BufferedWriter(new FileWriter("Atest\\count.txt"));
bw.write(count+"");
bw.close();
}
}
(5)存在如下文件,请使用IO流依据首个字符对其进行排序并写出到文件
3.侍中、侍郎郭攸之、费祎、董允等,此皆良实,志虑忠纯,是以先帝简拔以遗陛下。愚以为宫中之事,事无大小,悉以咨之,然后施行,必得裨补阙漏,有所广益。
8.愿陛下托臣以讨贼兴复之效,不效,则治臣之罪,以告先帝之灵。若无兴德之言,则责攸之、祎、允等之慢,以彰其咎;陛下亦宜自谋,以咨诹善道,察纳雅言,深追先帝遗诏,臣不胜受恩感激。
4.将军向宠,性行淑均,晓畅军事,试用之于昔日,先帝称之曰能,是以众议举宠为督。愚以为营中之事,悉以咨之,必能使行阵和睦,优劣得所。
2.宫中府中,俱为一体,陟罚臧否,不宜异同。若有作奸犯科及为忠善者,宜付有司论其刑赏,以昭陛下平明之理,不宜偏私,使内外异法也。
1.先帝创业未半而中道崩殂,今天下三分,益州疲弊,此诚危急存亡之秋也。然侍卫之臣不懈于内,忠志之士忘身于外者,盖追先帝之殊遇,欲报之于陛下也。诚宜开张圣听,以光先帝遗德,恢弘志士之气,不宜妄自菲薄,引喻失义,以塞忠谏之路也。
9.今当远离,临表涕零,不知所言。
6.臣本布衣,躬耕于南阳,苟全性命于乱世,不求闻达于诸侯。先帝不以臣卑鄙,猥自枉屈,三顾臣于草庐之中,咨臣以当世之事,由是感激,遂许先帝以驱驰。后值倾覆,受任于败军之际,奉命于危难之间,尔来二十有一年矣。
7.先帝知臣谨慎,故临崩寄臣以大事也。受命以来,夙夜忧叹,恐付托不效,以伤先帝之明,故五月渡泸,深入不毛。今南方已定,兵甲已足,当奖率三军,北定中原,庶竭驽钝,攘除奸凶,兴复汉室,还于旧都。此臣所以报先帝而忠陛下之职分也。至于斟酌损益,进尽忠言,则攸之、祎、允之任也。
5.亲贤臣,远小人,此先汉所以兴隆也;亲小人,远贤臣,此后汉所以倾颓也。先帝在时,每与臣论此事,未尝不叹息痛恨于桓、灵也。侍中、尚书、长史、参军,此悉贞良死节之臣,愿陛下亲之信之,则汉室之隆,可计日而待也。
实现代码如下:
import java.io.*;
import java.util.TreeMap;
public class IOTest5 {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new FileReader("Atest\\csb.txt"));
TreeMap<Integer, String> treeMap = new TreeMap<>();
String line;
while ((line = br.readLine()) != null) {
int number = Integer.parseInt(line.split("\\.")[0]);
String content = line.split("\\.")[1];
treeMap.put(number, content);
}
br.close();
//treeMap.forEach((k, v) -> System.out.println(k + ":" + v));
BufferedWriter bw = new BufferedWriter(new FileWriter("Atest\\csb_sorted.txt"));
treeMap.forEach((key, value) -> {
try {
bw.write(key + "." + value);
bw.newLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
});
bw.close();
}
}
法二
import java.io.*;
import java.util.*;
public class IOTest5Case2 {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new FileReader("Atest\\csb.txt"));
ArrayList<String> arr = new ArrayList<>();
String line;
while ((line = br.readLine()) != null) {
arr.add(line);
}
br.close();
arr.sort((o1, o2) -> {
int n1 = Integer.parseInt(o1.split("\\.")[0]);
int n2 = Integer.parseInt(o2.split("\\.")[0]);
return n1 - n2;
});
BufferedWriter bw = new BufferedWriter(new FileWriter("Atest\\csb_sorted.txt"));
for (String s : arr) {
bw.write(s);
bw.newLine();
}
bw.close();
}
}
(6)超大文件拷贝不同方法效率测试
import java.io.*;
public class IOTest6 {
public static void main(String[] args) throws IOException {
long startTime = System.currentTimeMillis();
// func1(); // 非常慢,预估至少要几十分钟至好几个小时
// func2(); // 时间开销:6s
// func3(); // 时间开销:24s
func4(); // 时间开销:6s
long endTime = System.currentTimeMillis();
System.out.println("时间开销:" + (endTime - startTime)/1000 + "s");
}
public static void func1() throws IOException {
System.out.println("拷贝中...");
FileInputStream fis = new FileInputStream("Atest\\ubuntu-20.04.6-desktop-amd64.iso");
FileOutputStream fos = new FileOutputStream("aTest\\ubuntuCopy.iso");
int b;
while ((b = fis.read()) != -1) {
fos.write(b);
}
fos.close();
fis.close();
}
public static void func2() throws IOException {
System.out.println("拷贝中...");
FileInputStream fis = new FileInputStream("Atest\\ubuntu-20.04.6-desktop-amd64.iso");
FileOutputStream fos = new FileOutputStream("aTest\\ubuntuCopy.iso");
byte[] bytes = new byte[8192];
int len;
while ((len = fis.read(bytes)) != -1) {
fos.write(bytes);
}
fos.close();
fis.close();
}
public static void func3() throws IOException {
System.out.println("拷贝中...");
BufferedInputStream bis = new BufferedInputStream(new FileInputStream("Atest\\ubuntu-20.04.6-desktop-amd64.iso"));
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("aTest\\ubuntuCopy.iso"));
int b;
while ((b = bis.read()) != -1) {
bos.write(b);
}
bos.close();
bis.close();
}
public static void func4() throws IOException {
System.out.println("拷贝中...");
BufferedInputStream bis = new BufferedInputStream(new FileInputStream("Atest\\ubuntu-20.04.6-desktop-amd64.iso"));
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("aTest\\ubuntuCopy.iso"));
byte[] bytes = new byte[8192];
int len;
while ((len = bis.read(bytes)) != -1) {
bos.write(bytes);
}
bos.close();
bis.close();
}
}
(7)对象输出、输入流
import java.io.*;
import java.util.ArrayList;
public class IOTest7 {
public static void main(String[] args) throws IOException, ClassNotFoundException {
// serialize();
deserialize();
}
public static void serialize() throws IOException {
ArrayList<Student> students = new ArrayList<>();
students.add(new Student("Li", 22));
students.add(new Student("zhang", 21));
students.add(new Student("Hua", 23));
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("Atest\\students.ser"));
oos.writeObject(students);
oos.close();
}
public static void deserialize() throws FileNotFoundException, IOException, ClassNotFoundException {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("Atest\\students.ser"));
ArrayList<Student> arr = (ArrayList<Student>) ois.readObject();
ois.close();
arr.forEach(System.out::println);
}
}
(8)在网上找到百家姓、男生名以及女生名网页,使用爬虫技术爬取对应信息,并以如下格式写入到文件当中
格式
龚江杉-男-21
丁晋远-男-20
奚泽胜-男-22
郝紫凡-女-19
范芷灵-女-19
於念雁-女-22
代码如下
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Exe1 {
public static void main(String[] args) throws IOException {
String familyNameURL = "https://hanyu.baidu.com/shici/detail?pid=0b2f26d4c0ddb3ee693fdb1137ee1b0d&from=kg0";
String boyNameURL = "http://www.haoming8.cn/baobao/10881.html";
String girlNameURL = "http://www.haoming8.cn/baobao/7641.html";
String familyNameHtml = WebCrawer(familyNameURL);
String boyNameHtml = WebCrawer(boyNameURL);
String girlNameHtml = WebCrawer(girlNameURL);
ArrayList<String> familyNameTempList = getData(familyNameHtml, "([^\\w]{4})(,|。)", 1);
// ArrayList<String> boyNameTempList = getData(boyNameHtml, "([^\\w]{2})(、|。)", 1); // 我这个正则表达式也能匹配
ArrayList<String> boyNameTempList = getData(boyNameHtml, "([\\u4E00-\\u9FA5]{2})(、|。)", 1);
ArrayList<String> girlNameTempList = getData(girlNameHtml, "(.. ){4}..", 0);
//System.out.println(girlNameTempList);
ArrayList<String> familyNameList = new ArrayList<>();
for (String familyName : familyNameTempList) {
for (int i = 0; i < familyName.length(); i++) {
char ch = familyName.charAt(i);
if (!familyNameList.contains(ch+"")){
familyNameList.add(ch+"");
}
}
}
ArrayList<String> boyNameList = new ArrayList<>();
for (String boyName : boyNameTempList) {
if (!boyNameList.contains(boyName)){
boyNameList.add(boyName);
}
}
ArrayList<String> girlNameList = new ArrayList<>();
for (String girlName : girlNameTempList) {
String[] temp = girlName.split(" ");
for (String name : temp) {
if (!girlNameList.contains(name)){
girlNameList.add(name);
}
}
}
ArrayList<String> infos = getInfo(familyNameList, boyNameList, girlNameList, 70, 50);
System.out.println(infos);
BufferedWriter bw = new BufferedWriter(new FileWriter("myiotest\\names.txt"));
for (String info : infos) {
bw.write(info+"\n");
}
bw.close();
}
public static ArrayList<String> getInfo(ArrayList<String> familyNameList, ArrayList<String> boyNameList, ArrayList<String> girlNameList, int boyCount, int girlCount) {
HashSet<String> boyHashSet = new HashSet<>();
while (true) {
if (boyHashSet.size() == boyCount) {
break;
}
Collections.shuffle(familyNameList);
Collections.shuffle(boyNameList);
boyHashSet.add(familyNameList.get(0) + boyNameList.get(0));
}
HashSet<String> girlHashSet = new HashSet<>();
while (true) {
if (girlHashSet.size() == girlCount) {
break;
}
Collections.shuffle(familyNameList);
Collections.shuffle(girlNameList);
girlHashSet.add(familyNameList.get(0) + girlNameList.get(0));
}
ArrayList<String> list = new ArrayList<>();
Random random = new Random();
for (String str : boyHashSet) {
int age = random.nextInt(10) + 18;
list.add(str + "-男-" + age);
}
for (String str : girlHashSet) {
int age = random.nextInt(8) + 18;
list.add(str + "-女-" + age);
}
return list;
}
public static ArrayList<String> getData(String str, String regex, int index){
Pattern compile = Pattern.compile(regex);
Matcher matcher = compile.matcher(str);
ArrayList<String> list = new ArrayList<>();
while(matcher.find()){
list.add(matcher.group(index));
}
return list;
}
private static String WebCrawer(String net) throws IOException {
StringBuilder stringBuilder = new StringBuilder();
URL url = new URL(net);
URLConnection conn = url.openConnection();
InputStreamReader isr = new InputStreamReader(conn.getInputStream());
int b;
while ((b = isr.read()) != -1) {
stringBuilder.append((char) b);
}
return stringBuilder.toString();
}
}
(9)基于前面抽取生成的随机姓名进行点名
public class Exe2 {
public static void main(String[] args) throws IOException {
ArrayList<String> infoList = getInfo("myiotest\\names.txt");
//System.out.println(infoList);
Collections.shuffle(infoList);
String name = infoList.get(0).split("-")[0];
System.out.println(name);
}
public static ArrayList<String> getInfo(String filepath) throws IOException {
ArrayList<String> list = new ArrayList<>();
BufferedReader br = new BufferedReader(new FileReader(filepath));
String str;
while ((str = br.readLine()) != null) {
list.add(str);
}
br.close();
return list;
}
}
(10)读取出姓名文件,并将其分为男女两个列表进行点名,令男生被点到的概率为0.7,女生被点到的概率为0,3,点名一百万次,统计男生女生分别被点到的次数,查看是否接近于7。
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Random;
public class Exe3 {
public static void main(String[] args) throws IOException {
ArrayList<String> infoList = getInfo("myiotest\\names.txt");
//System.out.println(infoList);
ArrayList<String> boyList = new ArrayList<>();
ArrayList<String> girlList = new ArrayList<>();
for (String info : infoList) {
String gender = info.split("-")[1];
if (gender.equals("男")) {
boyList.add(info);
} else {
girlList.add(info);
}
}
int[] probability = {1, 1, 1, 1, 1, 1, 1, 0, 0, 0};
Random rand = new Random();
int count = 0;
HashMap<String, Integer> genderRatio = new HashMap<>();
while (count++ < 1000000) {
int index = rand.nextInt(probability.length);
int boyOrGirl = probability[index];
if (boyOrGirl == 1){
Collections.shuffle(boyList);
String info = boyList.get(0);
String gender = info.split("-")[1];
if (!genderRatio.containsKey(gender)){
genderRatio.put(gender, 1);
} else {
genderRatio.put(gender, genderRatio.get(gender) + 1);
}
/*String boyName = boyList.get(0).split("-")[0];
System.out.println(boyName);*/
} else {
Collections.shuffle(girlList);
String info = girlList.get(0);
String gender = info.split("-")[1];
if (!genderRatio.containsKey(gender)){
genderRatio.put(gender, 1);
} else {
genderRatio.put(gender, genderRatio.get(gender) + 1);
}
/*String girlName = girlList.get(0).split("-")[0];
System.out.println(girlName);*/
}
}
int boyCount = genderRatio.get("男");
int girlCount = genderRatio.get("女");
System.out.println("男: " + boyCount + ", 女: " + girlCount + ", 比例: " + boyCount * 1.0/girlCount);
}
public static ArrayList<String> getInfo(String filepath) throws IOException {
ArrayList<String> list = new ArrayList<>();
BufferedReader br = new BufferedReader(new FileReader(filepath));
String str;
while ((str = br.readLine()) != null) {
list.add(str);
}
br.close();
return list;
}
}
(11)读取姓名文件进行随机点名,要求第三次点到的必须为指定的某一个人。
import java.io.*;
import java.util.ArrayList;
import java.util.Collections;
public class Exe4 {
public static void main(String[] args) throws IOException {
ArrayList<String> infoList = getInfo("myiotest\\names.txt");
//System.out.println(infoList);
//Collections.shuffle(infoList);
String theChosenOne = infoList.get(15);
System.out.println("the chosen one: " + theChosenOne);
System.out.println("---------------------------------");
BufferedReader br = new BufferedReader(new FileReader("myiotest\\rollCallCount.txt"));
int rollCallCount = Integer.parseInt(br.readLine());
rollCallCount++;
if (rollCallCount != 3) {
Collections.shuffle(infoList);
String name = infoList.get(0).split("-")[0];
System.out.println(name);
} else {
String name = theChosenOne.split("-")[0];
System.out.println(name);
}
BufferedWriter bw = new BufferedWriter(new FileWriter("myiotest\\rollCallCount.txt"));
bw.write(rollCallCount+"");
bw.close();
}
public static ArrayList<String> getInfo(String filepath) throws IOException {
ArrayList<String> list = new ArrayList<>();
BufferedReader br = new BufferedReader(new FileReader(filepath));
String str;
while ((str = br.readLine()) != null) {
list.add(str);
}
br.close();
return list;
}
}
(12)假设一个班上包含5名男生和5名女生,对其进行随机点名,要求点到的名字不能重复,所有人都点完之后可以自动从头开始点名。
import java.io.*;
import java.util.ArrayList;
import java.util.Collections;
public class Exe5 {
public static void main(String[] args) throws IOException {
ArrayList<String> infoList = getInfo("myiotest\\names.txt");
//System.out.println(infoList);
ArrayList<String> boyList = new ArrayList<>();
ArrayList<String> girlList = new ArrayList<>();
for (String info : infoList) {
String gender = info.split("-")[1];
if (gender.equals("男")) {
boyList.add(info);
} else {
girlList.add(info);
}
}
ArrayList<String> peopleInClass = new ArrayList<>();
for (int i = 0; i < 5; i++) {
peopleInClass.add(boyList.get(i));
peopleInClass.add(girlList.get(i));
}
Collections.shuffle(peopleInClass);
ArrayList<String> rollCalledList = new ArrayList<>();
BufferedReader br = new BufferedReader(new FileReader("myiotest\\rollCalled.txt"));
String str;
while ((str = br.readLine()) != null) {
rollCalledList.add(str);
}
if (rollCalledList.size() != peopleInClass.size()) {
takeRollCall(rollCalledList, peopleInClass, "myiotest\\rollCalled.txt");
} else {
rollCalledList.clear();
BufferedWriter bw = new BufferedWriter(new FileWriter("myiotest\\rollCalled.txt"));
bw.close();
takeRollCall(rollCalledList, peopleInClass, "myiotest\\rollCalled.txt");
}
}
public static void takeRollCall(ArrayList<String> rollCalledList, ArrayList<String> peopleInClass, String filePath) throws IOException {
String info;
do {
Collections.shuffle(peopleInClass);
info = peopleInClass.get(0);
} while (rollCalledList.contains(info));
rollCalledList.add(info);
System.out.println(info.split("-")[0]);
BufferedWriter bw = new BufferedWriter(new FileWriter(filePath));
for (String s : rollCalledList) {
bw.write(s+"\n");
}
bw.close();
}
public static ArrayList<String> getInfo(String filepath) throws IOException {
ArrayList<String> list = new ArrayList<>();
BufferedReader br = new BufferedReader(new FileReader(filepath));
String str;
while ((str = br.readLine()) != null) {
list.add(str);
}
br.close();
return list;
}
}
(13)一个txt文件中存有如username=admin&password=123456&count=0
格式的内容,要求用户输入用户名密码,若登录错误则增加count值,超过三次则不能再登录,自动锁定账号。在3次及以前若输入正确则归零。
基本登录逻辑
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
public class Exe6 {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new FileReader("myiotest\\userInfo.txt"));
String s = br.readLine();
br.close();
String usernameR = s.split("&")[0].split("=")[1];
String passwordR = s.split("&")[1].split("=")[1];
Scanner scanner = new Scanner(System.in);
System.out.println("Input username: ");
String username = scanner.nextLine();
System.out.println("Input password: ");
String password = scanner.nextLine();
if (username.equals(usernameR) && password.equals(passwordR)) {
System.out.println("You are logged in!");
} else {
System.out.println("Login failed! Check your username and password.");
}
}
}
完整登录逻辑
import java.io.*;
import java.util.Scanner;
public class Exe7 {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new FileReader("myiotest\\userInfo.txt"));
String s = br.readLine();
br.close();
String usernameR = s.split("&")[0].split("=")[1];
String passwordR = s.split("&")[1].split("=")[1];
int count = Integer.parseInt(s.split("&")[2].split("=")[1]);
if (count < 3) {
Scanner scanner = new Scanner(System.in);
System.out.println("Input username: ");
String username = scanner.nextLine();
System.out.println("Input password: ");
String password = scanner.nextLine();
if (username.equals(usernameR) && password.equals(passwordR)) {
System.out.println("You are logged in!");
count = 0;
} else {
System.out.println("Login failed! Check your username and password.");
count++;
if (count == 3) {
System.out.println("You have tried 3 times, your account is locked!");
}
}
BufferedWriter bw = new BufferedWriter(new FileWriter("myiotest\\userInfo.txt"));
bw.write("username=" + usernameR + "&password=" + passwordR + "&count=" +count + "\n");
bw.close();
} else {
System.out.println("Your account is locked! Please contact your administrator.");
}
}
}
9、多线程
(1)车站有两个窗口售票,总共又1000张票,售完即止。请使用多线程相关内容实现代码。
自定义多线程
public class Window extends Thread{
public static int ticketNum = 1000;
@Override
public void run() {
while(true){
synchronized (Window.class){
if(ticketNum <= 0){
break;
} else {
Window.ticketNum--;
System.out.println(getName() + "出售了1张票,剩余" + ticketNum);
try {
Thread.sleep(10);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
}
}
}
主函数
public class Main {
public static void main(String[] args) {
Window win1 = new Window();
Window win2 = new Window();
win1.setName("窗口1");
win2.setName("窗口2");
new Thread(win1).start();
new Thread(win2).start();
}
}
(2)启用两个线程共同1-100之间的偶数
自定义线程
public class MyThread extends Thread {
public static int number = 0;
@Override
public void run() {
while (true) {
synchronized (MyThread.class) {
if (number > 100) {
break;
} else {
if (number % 2 != 0) {
System.out.println(getName() + ": " + number);
}
number++;
try {
Thread.sleep(5);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
}
}
}
主函数
public class Main {
public static void main(String[] args) {
MyThread t1 = new MyThread();
MyThread t2 = new MyThread();
t1.setName("t1");
t2.setName("t2");
new Thread(t1).start();
new Thread(t2).start();
}
}
(3)分发礼物
自定义线程
public class MyThread extends Thread {
public static int gifts = 100;
@Override
public void run() {
while (true) {
synchronized (MyThread.class) {
if (gifts < 10) {
break;
} else {
System.out.println(getName() + " gifts: " + gifts);
MyThread.gifts--;
try {
Thread.sleep(3);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
}
}
}
主函数
public class Main {
public static void main(String[] args) {
MyThread t1 = new MyThread();
MyThread t2 = new MyThread();
t1.setName("t1");
t2.setName("t2");
new Thread(t1).start();
new Thread(t2).start();
}
}
(4)抢红包,总共100元,分成3个红包,5个人抢。抢到红包的显示金额,没抢到的打印没有抢到。
自定义线程
import java.util.Random;
public class MyThread extends Thread {
public static int money = 100;
public static int counter = 3;
public static Random rand = new Random();
boolean flag = false;
@Override
public void run() {
while (true) {
synchronized (MyThread.class) {
if (counter <= 0 || money <= 0) {
if (!this.flag){
System.out.println(getName() + "没有抢到红包");
this.flag = true;
}
break;
} else {
if (!this.flag){
if (counter > 1){
int currentMoney = rand.nextInt(1,money + 1);
MyThread.money -= currentMoney;
MyThread.counter--;
System.out.println(getName() + "抢到了" + currentMoney + "元, 剩余"+ MyThread.counter +"个红包, 剩余红包金额为" + MyThread.money);
} else {
int currentMoney = MyThread.money;
MyThread.money = 0;
MyThread.counter--;
System.out.println(getName() + "抢到了" + currentMoney + "元, 剩余"+ MyThread.counter +"个红包, 剩余红包金额为" + MyThread.money);
}
try {
Thread.sleep(6);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
this.flag = true;
}
}
}
}
}
}
主函数
public class Main {
public static void main(String[] args) {
MyThread t1 = new MyThread();
MyThread t2 = new MyThread();
MyThread t3 = new MyThread();
MyThread t4 = new MyThread();
MyThread t5 = new MyThread();
t1.setName("t1");
t2.setName("t2");
t3.setName("t3");
t4.setName("t4");
t5.setName("t5");
new Thread(t1).start();
new Thread(t2).start();
new Thread(t3).start();
new Thread(t4).start();
new Thread(t5).start();
}
}
(5)总共有奖项{"10元大奖", "5元大奖", "20元大奖", "100元大奖", "200元大奖", "500元大奖","800元大奖", "2元大奖", "80元大奖", "300元大奖", "700元大奖", "50元大奖"}
,共有两个抽奖箱,请使用多线程思想模拟抽奖
自定义线程类
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Random;
public class MyThread extends Thread {
private final static String[] array = {"10元大奖", "5元大奖", "20元大奖", "100元大奖", "200元大奖", "500元大奖",
"800元大奖", "2元大奖", "80元大奖", "300元大奖", "700元大奖", "50元大奖"};
public static ArrayList<String> list = new ArrayList<>(Arrays.asList(array));
public static Random random = new Random();
@Override
public void run() {
while (true) {
synchronized (MyThread.class) {
if (list.isEmpty()) {
break;
} else {
int index = random.nextInt(list.size());
System.out.println(getName() + "又产生了一个" + list.get(index));
list.remove(index);
try {
Thread.sleep(10);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
}
}
}
主函数
public class Main {
public static void main(String[] args) {
MyThread t1 = new MyThread();
MyThread t2 = new MyThread();
t1.setName("抽奖箱1");
t2.setName("抽奖箱2");
new Thread(t1).start();
new Thread(t2).start();
}
}
(6)奖项依然如第(5)所示,现有三个抽奖箱,但是最后需要打印总共多少个奖项,最高奖项为多少,哪一个抽奖箱诞生了最大奖项,金额为多少
自定义线程类
import java.util.*;
public class MyThread extends Thread {
private final static Integer[] array = {10, 5, 20, 100, 200, 500, 800, 2, 80, 300, 700, 50};
public static ArrayList<Integer> list = new ArrayList<>(Arrays.asList(array));
public static Random random = new Random();
public static HashMap<String, ArrayList<Integer>> counterMap = new HashMap<>();
public static boolean flag = false;
@Override
public void run() {
while (true) {
synchronized (MyThread.class) {
if (list.isEmpty()) {
if (!MyThread.flag) {
int totalMax = 0;
String maxName = null;
for (String tName : MyThread.counterMap.keySet()) {
System.out.println("在此次抽奖过程中, " + tName + "共产生了" + MyThread.counterMap.get(tName).size() + "个奖项。");
System.out.print("分别为:");
StringJoiner sj = new StringJoiner(", ", "", "");
int max = 0;
int sum = 0;
for (Integer money : MyThread.counterMap.get(tName)) {
sj.add(money + "");
if (money > max) {
max = money;
}
sum += money;
}
System.out.println(sj.toString() + "。最高奖项为: " + max + ", 总金额为: " + sum + "元。");
if (max > totalMax) {
totalMax = max;
maxName = tName;
}
}
System.out.println("在此次抽奖过程中, " + maxName + "产生了最大奖项, 该奖项金额为: " + totalMax + "元。");
MyThread.flag = true;
}
break;
} else {
int index = random.nextInt(list.size());
int money = list.get(index);
String tName = getName();
if (!counterMap.containsKey(tName)) {
counterMap.put(tName, new ArrayList<Integer>());
}
counterMap.get(tName).add(money);
list.remove(index);
try {
Thread.sleep(10);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
}
}
}
主函数
public class Main {
public static void main(String[] args) {
MyThread t1 = new MyThread();
MyThread t2 = new MyThread();
MyThread t3 = new MyThread();
t1.setName("抽奖箱1");
t2.setName("抽奖箱2");
t3.setName("抽奖箱3");
new Thread(t1).start();
new Thread(t2).start();
new Thread(t3).start();
}
}
(7)生产者消费者:经典的生产者消费者模型,具体要求就不再赘述
生产者类
public class Producer extends Thread {
@Override
public void run() {
while (true) {
synchronized (Store.lock) {
if (Store.count >= 10) {
break;
} else {
if (Store.flag == 0) {
System.out.println(getName() + ": 仓库进货");
Store.flag = 1;
Store.lock.notifyAll();
} else {
try {
Store.lock.wait();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
}
}
}
}
消费者类
public class Consumer extends Thread {
@Override
public void run() {
while (true) {
synchronized (Store.lock) {
if (Store.count >= 10){
break;
} else {
if (Store.flag == 1){
System.out.println(getName() + ": 仓库出货, 总出货量: " + (Store.count + 1));
Store.flag = 0;
Store.count++;
Store.lock.notifyAll();
} else {
try {
Store.lock.wait();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
}
}
}
}
仓库
public class Store {
public static int flag = 0;
public static int count = 0;
public static final Object lock = new Object();
}
主函数
public class Main {
public static void main(String[] args) {
Producer producer = new Producer();
Consumer consumer = new Consumer();
producer.setName("Producer");
consumer.setName("Consumer");
new Thread(producer).start();
new Thread(consumer).start();
}
}
10、网络编程
(1)利用TCP协议实现客户端向服务器端发送信息
客户端
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.Scanner;
public class Client {
public static void main(String[] args) throws IOException {
Socket socket = new Socket("127.0.0.1", 10086);
Scanner scanner = new Scanner(System.in);
OutputStream os = socket.getOutputStream();
while (true){
System.out.println("请输入内容(停止程序请输入\"exit()\"): ");
String input = scanner.nextLine();
os.write(input.getBytes());
os.flush();
if(input.equals("exit()")){
break;
}
}
os.close();
socket.close();
}
}
服务器端
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static void main(String[] args) throws IOException {
ServerSocket ss = new ServerSocket(10086);
System.out.println("等待客户端连接...");
Socket socket = ss.accept();
System.out.println("客户端连接成功!等待用户发送消息:");
InputStream is = socket.getInputStream();
String ip = socket.getInetAddress().getHostAddress();
int port = socket.getPort();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
int b;
//StringBuffer sb = new StringBuffer();
while ((b = br.read()) != -1) {
System.out.print((char) b);
//sb.append((char) b);
}
//System.out.println("来自用户" + ip + ":" + port + "说: " + sb.toString());
socket.close();
ss.close();
}
}
(2)客户端发送信息,服务器端收到信息后并进行端
客户端
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Scanner;
public class Client {
public static void main(String[] args) throws IOException {
Socket socket = new Socket("127.0.0.1", 10086);
OutputStream os = socket.getOutputStream();
String input = "你好吗?";
os.write(input.getBytes());
os.flush();
socket.shutdownOutput();
InputStreamReader isr = new InputStreamReader(socket.getInputStream());
BufferedReader br = new BufferedReader(isr);
int b;
while ((b = br.read()) != -1) {
System.out.print((char) b);
}
os.close();
socket.close();
}
}
服务器端
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static void main(String[] args) throws IOException {
ServerSocket ss = new ServerSocket(10086);
System.out.println("等待客户端连接...");
Socket socket = ss.accept();
System.out.println("客户端连接成功!等待用户发送消息:");
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
int b;
//StringBuffer sb = new StringBuffer();
while ((b = br.read()) != -1) {
System.out.print((char) b);
//sb.append((char) b);
}
//System.out.println("来自用户" + ip + ":" + port + "说: " + sb.toString());
OutputStream os = socket.getOutputStream();
String str = "我很好!";
os.write(str.getBytes());
os.flush();
socket.close();
ss.close();
}
}
(3)客户端向服务器端上传文件,若上传成功服务器端要返回相应信息
客户端
import java.io.*;
import java.net.Socket;
public class Client {
public static void main(String[] args) throws IOException {
Socket socket = new Socket("127.0.0.1", 10086);
OutputStream os = socket.getOutputStream();
FileInputStream fis = new FileInputStream("Atest\\Li.jpg");
System.out.println("正在上传文件...");
int b;
while ((b = fis.read()) != -1) {
os.write(b);
}
os.flush();
fis.close();
socket.shutdownOutput();
System.out.println("文件上传结束");
InputStreamReader isr = new InputStreamReader(socket.getInputStream());
BufferedReader br = new BufferedReader(isr);
System.out.println("服务器提示信息: ");
int a;
while ((a = br.read()) != -1) {
System.out.print((char) a);
}
socket.close();
}
}
服务器端
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static void main(String[] args) throws IOException {
ServerSocket ss = new ServerSocket(10086);
System.out.println("等待客户端连接...");
Socket socket = ss.accept();
InputStream is = socket.getInputStream();
FileOutputStream fos = new FileOutputStream("Atest\\Li_upload.jpg");
System.out.println("链接成功,正在接收文件...");
int b;
while ((b = is.read()) != -1) {
fos.write(b);
}
fos.close();
System.out.println("接收完成,已返回提示信息");
socket.shutdownInput();
OutputStream os = socket.getOutputStream();
os.write("服务器端已成功接收!".getBytes());
os.flush();
socket.close();
ss.close();
}
}