java 对txt文件读写(已经封装好)
读文件:
1 public static String readTxt(String txtPath) { 2 File file = new File(txtPath); 3 if(file.isFile() && file.exists()){ 4 try { 5 FileInputStream fileInputStream = new FileInputStream(file); 6 InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream); 7 BufferedReader bufferedReader = new BufferedReader(inputStreamReader); 8 9 StringBuffer sb = new StringBuffer(); 10 String text = null; 11 while((text = bufferedReader.readLine()) != null){ 12 sb.append(text); 13 } 14 return sb.toString(); 15 } catch (Exception e) { 16 e.printStackTrace(); 17 } 18 } 19 return null; 20 }
写文件:
1 public static void writeTxt(String txtPath,String content){ 2 FileOutputStream fileOutputStream = null; 3 File file = new File(txtPath); 4 try { 5 if(file.exists()){ 6 //判断文件是否存在,如果不存在就新建一个txt 7 file.createNewFile(); 8 } 9 fileOutputStream = new FileOutputStream(file,true);//多个true就是追加 10 fileOutputStream.write(content.getBytes()); 11 fileOutputStream.flush(); 12 fileOutputStream.close(); 13 } catch (Exception e) { 14 e.printStackTrace(); 15 } 16 }
完整代码:
1 import java.io.BufferedReader; 2 import java.io.File; 3 import java.io.FileInputStream; 4 import java.io.FileOutputStream; 5 import java.io.InputStreamReader; 6 public class 文件读写 { 7 public static String readTxt(String txtPath) { 8 File file = new File(txtPath); 9 if(file.isFile() && file.exists()){ 10 try { 11 FileInputStream fileInputStream = new FileInputStream(file); 12 InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream); 13 BufferedReader bufferedReader = new BufferedReader(inputStreamReader); 14 15 StringBuffer sb = new StringBuffer(); 16 String text = null; 17 while((text = bufferedReader.readLine()) != null){ 18 sb.append(text); 19 } 20 return sb.toString(); 21 } catch (Exception e) { 22 e.printStackTrace(); 23 } 24 } 25 return null; 26 } 27 public static void writeTxt(String txtPath,String content){ 28 FileOutputStream fileOutputStream = null; 29 File file = new File(txtPath); 30 try { 31 if(file.exists()){ 32 //判断文件是否存在,如果不存在就新建一个txt 33 file.createNewFile(); 34 } 35 fileOutputStream = new FileOutputStream(file,true);//多个true就是追加 36 fileOutputStream.write(content.getBytes()); 37 fileOutputStream.flush(); 38 fileOutputStream.close(); 39 } catch (Exception e) { 40 e.printStackTrace(); 41 } 42 } 43 }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· C#/.NET/.NET Core技术前沿周刊 | 第 29 期(2025年3.1-3.9)
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异