Java IO流 (1)------保存文件与读取文件
1、写入读取封装步骤
/* * 1.写入 * 1)指定文件路径以及文件名 * 2)判断文件夹以及文件是否存在 * 3)创建文件以及文件夹 * 4)输出流 * 5)写入 * 6)转换 * 2.读取 * 1)指定路径 * 2)判断文件路径是否存在 * 3)判断是否是文件名 * 4)字符流 * 5)read出来的是单个单个的字符,用StringBuilder来拼接 * 6)while循环 * 3.封装 * 1)new对象 * 2)set装载 */
2、创建
1 public static File createNote(String type, String fileName) { 2 //new一个File类,并传入路径 3 File file = new File(CommanPath.PATH.getValue()); 4 5 //写入需要判断文件夹是否存在,不存在则创建,读取不需要 6 if (!"read".equals(type)) { 7 //判断文件夹是否存在,不存在则先创建 8 if (!file.exists()) { 9 file.mkdirs(); 10 } 11 } 12 //在new一个file类,传入路径以及文件名 13 File file1 = new File(CommanPath.PATH.getValue(), fileName); 14 if (!"read".equals(type)) { 15 //判断文件是否存在,不存在则先创建 16 try { 17 if (!file1.isFile()) { 18 file1.createNewFile(); 19 } 20 } catch (IOException e) { 21 e.printStackTrace(); 22 } 23 } 24 25 return file1; 26 }
3、写入
1 /** 2 * 写入 3 */ 4 private void writeMessage() { 5 File file = IoUtil.createNote("write", Constant.MESSAGE_NAME); 6 try { 7 OutputStream outputStream = new FileOutputStream(file); 8 IoMessageModel ioMessageModel = new IoMessageModel(); 9 outputStream.write(ioMessageModel.getMessageDescription().getBytes()); 10 outputStream.close(); 11 } catch (IOException e) { 12 e.printStackTrace(); 13 } 14 }
4、读取
1 /** 2 * 读取记事本 3 * 4 * @return 字符流数据 5 */ 6 public static String readNote(String fileName) { 7 //找到文件地址以及文件名 8 File file = createNote("read", fileName); 9 /* 10 String 不可变字符串,字符串拼接时效率低,浪费内存 11 StringBuffer 可变字符串,线程安全,多线程操作 12 StringBuilder 可变字符串,线程不安全,单线程操作,速度最快。在操作可变字符串时一般用StringBuilder, 13 如果考虑线程安全则必须使用StringBuffer 14 */ 15 StringBuilder result = new StringBuilder(); 16 try { 17 /* 18 * 字节流,会出现乱码 19 */ 20 /* InputStream inputStream = new FileInputStream(file); 21 int data; 22 while ((data=inputStream.read())>0){ 23 System.out.print((char) data); 24 }*/ 25 /* 26 * 字符流 27 */ 28 Reader reader = new FileReader(file); 29 int data; 30 while ((data = reader.read()) > 0) { 31 result.append((char) data); 32 } 33 } catch (IOException e) { 34 e.printStackTrace(); 35 } 36 //将StringBuiler转换为String 37 return result.toString(); 38 }
5、枚举类
1 /** 2 * @author liangd 3 * date 2020-10-13 12:57 4 * code 枚举类 5 */ 6 public enum CommanPath { 7 //标识符 8 AA("@#%"), 9 //定义文件路径 10 PATH("E:\\liangd\\note"); 11 12 private String value; 13 14 //构造方法 15 CommanPath(String value) { 16 this.value = value; 17 } 18 19 public String getValue() { 20 return value; 21 } 22 }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix