IO流----读取文件,复制文件,追加/插入文件
文件结构

读取文件
第一种方式
public class Test { public static void main(String[] args) throws IOException {
// 最好别用FileReader,容易漏读 // 如果是window系统,/需要换成\ FileInputStream in = new FileInputStream("/Users/mac/eclipse-workspace/Demo/src/Test/file.txt"); byte[] buffer = new byte[1024]; int len = 0; while((len=in.read(buffer))!=-1) { System.out.println(new String(buffer,0,len)); } in.close(); // 一定记得关闭! } }
第二种方式:
public class Try { public static void main(String[] args) throws IOException { File file = new File("/Users/mac/Desktop/1.txt"); BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), "utf-8")); while (true) { String line = reader.readLine(); if(line==null) {break;} System.out.println(line); } } }
结果

复制文件
/* * 目标:把1.txt内容复制到2.txt */ File file = new File("/Users/mac/Desktop/1.txt"); File file2 = new File("/Users/mac/Desktop/2.txt"); @Test public void test1() throws IOException { FileInputStream in = new FileInputStream(file); FileOutputStream out = new FileOutputStream(file2); int len = 0; byte[] buffer = new byte[1024]; while ((len = in.read(buffer)) != -1) { out.write(buffer, 0, len); } }
追加/插入文件
追加:
一个文件插入另一个文件:
https://zhidao.baidu.com/question/583629736414603045.html
FileInputStream和FileOutputStream的简单用法
https://blog.csdn.net/qq_43750656/article/details/118355995
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!