Java IO流
/** * 读取文本 * @param path * @return */ public static String readText(String path) { StringBuilder sbr = null; File file = new File(path); FileInputStream fis = null; Reader reader = null; try { fis = new FileInputStream(file); reader = new InputStreamReader(fis, "UTF-8"); sbr = new StringBuilder(); int ch = 0; while ((ch = reader.read()) != -1) { sbr.append((char) ch); } } catch (IOException e) { } finally { try { if (fis != null) fis.close(); if (reader != null) reader.close(); } catch (IOException e) { } } return sbr == null ? null : sbr.toString(); } /** * 写入文本内容(默认覆盖) * @param msg 文本内容 * @param path 输出路径 * @return */ public static boolean writeToTxt(String msg, String path) { return writeToTxt(msg, path, false); } /** * 写入文本内容 * @param msg 文本内容 * @param path 输出路径 * @param append true:追加 / false:覆盖(默认) * @return */ public static boolean writeToTxt(String msg, String path, boolean append) { FileOutputStream fos = null; OutputStreamWriter osw = null; BufferedWriter bw = null; boolean rs = false; try { String filePath = path.substring(path.lastIndexOf(".") + 1); // 不存在则创建文件夹 File fileP = new File(filePath); if (!fileP.exists()) fileP.mkdirs(); // 文件对象 File file = new File(path); // 构建流 fos = new FileOutputStream(file, append); osw = new OutputStreamWriter(fos, "UTF-8"); bw = new BufferedWriter(osw); // 输出 bw.write(msg); bw.flush(); rs = true; } catch (IOException e) { System.out.println("输出文件异常"); } finally { try { if (fos != null) fos.close(); if (osw != null) osw.close(); if (bw != null) bw.close(); } catch (IOException e) {} } return rs; } /** * 获取当前操作系统桌面路径 * @return 返回以反斜杠结尾的字符串 */ public static String getDesktopPath() { File desktopDir = FileSystemView.getFileSystemView() .getHomeDirectory(); String desktopPath = desktopDir.getAbsolutePath(); if (desktopPath == null) { desktopPath = ""; } else if (!desktopPath.isEmpty() && !desktopPath.endsWith("/") && !desktopPath.endsWith("\\")) { if (desktopPath.indexOf("/") != -1) desktopPath += "/"; else if (desktopPath.indexOf("\\") != -1) desktopPath += "\\"; } return desktopPath; }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)