【开发笔记】- Java写入、读取文本
文本写入
public static void createFile(String input) throws IOException {
//设置文件路径 String filePath = "D:/"; File dir = new File(filePath); // 一、检查放置文件的文件夹路径是否存在,不存在则创建 if (!dir.exists()) { dir.mkdirs();// mkdirs创建多级目录 } File checkFile = new File(filePath + "/SM3.txt"); FileWriter fw = null; try { // 二、检查目标文件是否存在,不存在则创建 if (!checkFile.exists()) { checkFile.createNewFile();// 创建目标文件 } // 三、向目标文件中写入内容 // FileWriter(File file, boolean append),append为true时为追加模式,false或缺省则为覆盖模式 fw = new FileWriter(checkFile, true); fw.write(input+"\r\n"); fw.flush(); } catch (IOException e) { e.printStackTrace(); } finally { if (null != fw) fw.close(); } }
文件读取
public static void readFile(String[] args) { try { BufferedReader in = new BufferedReader(new FileReader("test.log")); String str; while ((str = in.readLine()) != null) { System.out.println(str); } System.out.println(str); } catch (IOException e) { } }
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步