/**
* 一致student_info.txt文件中有一组数据按照格式【姓名-年龄-分数】存储
* 运用IO获取将该文件中的数据分别封装成5个student对象存入到集合中
* 要求根据学生的总分进行排序(降序),如果分数相同则比较年龄(降序)。并且输出展示
*/
private static void demo4() {
List
try (
BufferedReader reader = new BufferedReader(new FileReader("student_info.txt"))
) {
String s;
while ((s=reader.readLine())!=null){
String[] split = s.split("-");
students.add(new Student(split[0],Integer.parseInt(split[1]),Integer.parseInt(split[2])));
}
List
@Override
public int compare(Student o1, Student o2) {
return o2.getScore() - o1.getScore();
}
}.thenComparing(Student::getAge).reversed()).collect(Collectors.toList());
collect.forEach(System.out::println);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 使用集合相关功能,存储10个数据(1~50的随机偶数),要求数字不能重复,添加完成后从大到小倒序遍历输出到控制台
* 并且使用io流将集合中的元素按照指定格式输出到置顶文件中
*/
private static void demo3() {
ThreadLocalRandom random = ThreadLocalRandom.current();
Set<Integer> set = new HashSet<>(10);
while (set.size() < 20) {
int i = random.nextInt(1, 51);
if (i % 2 == 0)
set.add(i);
}
List<Integer> collect = set.stream().collect(Collectors.toList());
Collections.sort(collect, ((Integer o1, Integer o2) -> o2 - o1));
try (
OutputStream stream = new FileOutputStream("e.txt")
) {
String string = collect.toString();
stream.write(string.getBytes());
//[46, 44, 42, 40, 38, 36, 34, 32, 28, 24, 22, 20, 18, 16, 14, 12, 10, 8, 6, 4]
} catch (FileNotFoundException e) {
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 读取任意txt文件内容,并统计出这个文本中每个字符以及每个字符出现的次数,并且以下格式:
* 字符=次数,持久化保存在文件中
*/
private static void demo2() {
Map<String, Integer> map = new HashMap<>(16);
try (
BufferedReader reader = new BufferedReader(new FileReader("a.txt"));
BufferedWriter writer = new BufferedWriter(new FileWriter("c.txt"))
) {
int len;
while ((len = reader.read()) != -1) {
char a = (char) len;
String s = String.valueOf(a);
if (map.get(s) != null) {
map.put(s, map.get(s) + 1);
} else {
map.put(s, 1);
}
}
System.out.println(map);
Set<Map.Entry<String, Integer>> entries = map.entrySet();
for (Map.Entry<String, Integer> entry : entries) {
writer.write(entry.getKey());
writer.write("=");
writer.write(String.valueOf(entry.getValue()));
writer.newLine();
}
} catch (FileNotFoundException e) {
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 已知文件a.txt中的内容为:AAbcdea22dfewplkCC321ou1,
* 请编写程序读取该文件内容,要求去掉重复字母,并且按照自然顺序后输出到b.txt
*/
private static void demo1() {
try (
BufferedReader reader = new BufferedReader(new FileReader("a.txt"));
BufferedWriter writer = new BufferedWriter(new FileWriter("b.txt"))
) {
String s = reader.readLine();
char[] chars = s.toCharArray();
Arrays.sort(chars);
s = new String(chars);
s = s.replaceAll("(.)\\1+", "$1");
writer.write(s);
} catch (IOException e) {
e.printStackTrace();
}
}
标签:String,writer,collect,IO,catch,new,习题,txt
From: https://www.cnblogs.com/Liku-java/p/16960660.html