package com.io; import lombok.Data; import java.io.*; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.stream.Collectors; /** * @author LinQi * @version 1.0 * @date 2021/6/28 9:52 */ @Data class Article { private Integer id; private String name; private Double prices; private Integer count; } class Demo { public static void main(String[] args) { List<Article> list = new ArrayList<>(); String filePath = "d:/a.txt"; File file = new File(filePath); BufferedReader reader = null; String tempString = null; String str = null; try { reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8")); while ((tempString = reader.readLine()) != null) { str = tempString; Article article = new Article(); String[] split = str.split(","); article.setId(Integer.parseInt(split[0])); article.setName(split[1]); article.setPrices(Double.parseDouble(split[2])); article.setCount(Integer.parseInt(split[3])); list.add(article); } reader.close(); } catch ( Exception e) { e.printStackTrace(); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { e.printStackTrace(); } } } List<Article> collect = list.stream().sorted(Comparator.comparing(Article::getPrices).reversed()).collect(Collectors.toList()); File files = new File("d:/price_order.txt"); try { if (!files.exists()) { files.createNewFile(); } OutputStream os = new FileOutputStream(files); for (Article article : collect) { String st = article.getId()+","+article.getName()+","+ article.getPrices()+","+ article.getCount(); os.write(st.getBytes(StandardCharsets.UTF_8)); os.write(("\r\n").getBytes()); } os.close(); } catch (Exception e) { e.printStackTrace(); } } }
根据你的题目来看 ,可以创建一个类,IO根据行与,切割来设置类的属性值,再加入list中,读取完后使用stream排序,在写入txt中即可