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;
}

 

posted @ 2022-03-16 10:17  散人长情  阅读(14)  评论(0编辑  收藏  举报