package com.example.demo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import java.io.*; import java.util.*; @SpringBootApplication public class DemoApplication { public static void main(String[] args) throws IOException { // SpringApplication.run(DemoApplication.class, args); Map<Integer, String> read = readTxtFile("D:\\data\\list.txt"); List<String> strings = new ArrayList<>(1000);//初始容量为1000 final Iterator<Integer> iterator = read.keySet().iterator();//keySet()返回值,所有key;iterator()遍历 //当在缓冲区内扫描到字符时,会返回true, 否则会发生阻塞,等待数据输入。 //hasNext("World")匹配到对应字符返回true, while (iterator.hasNext()){ Integer key = iterator.next(); String s = read.get(key); System.out.println(s); strings.add(s); } writeTxtFile("D:\\data\\list1.txt",strings); } private static Map<Integer,String> readTxtFile(String filePath){ Map<Integer, String> txtMap = new HashMap<Integer,String>(1000);//<key,value> try(FileInputStream fileInputStream = new FileInputStream(filePath);//从文件系统中的某个文件中获得输入字节 InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream);//创建一个使用默认字符集的 InputStreamReader。字节转换为字符 BufferedReader bufferedReader = new BufferedReader(inputStreamReader);)//缓存区 BufferReader类用来包装所有其 read() 操作可能开销很高的 Reader(如 FileReader 和InputStreamReader)。 { String line = null; Integer i = 0; while ((line =bufferedReader.readLine())!=null){//readline() 方法用于从文件读取整行,包括 “\n” 字符 i=i+1; txtMap.put(i,line); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }return txtMap; } private static void writeTxtFile(String filePath,List<String> textList)throws IOException{ final File file = new File(filePath);//通过给定的父抽象路径名和子路径名字符串创建一个新的File实例 file.createNewFile(); try(FileWriter fileWriter =new FileWriter(file);//字符向流中写入数据 final BufferedWriter bufferedWriter = new BufferedWriter(fileWriter)){//BufferedWriter加入了缓冲技术,将字符读取对象作为参数 for (String text:textList){//循环textList赋值给text bufferedWriter.write(text);//text写入 bufferedWriter.newLine();//使用自己的行分隔符概念 } bufferedWriter.flush(); }catch (Exception e){ e.printStackTrace(); } } }
本文来自博客园,作者:阿霖找BUG,转载请注明原文链接:https://www.cnblogs.com/lin-07/p/17277916.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)