Java读取文件作为字符串

在平时的开发中,为了测试方便,经常会用到从文件中读取数据作为字符串的操作,这里主要记录Java读取文件的几种方法。

注意:以下方法主要是为了在debug的时候mock数据使用,如果文件过大,可能会导致OOM,慎用

1. 通过 BufferedReader 方式读取

通过BufferedReaderreadLine方法逐行读取

/**
 * 通过BufferedReader读取
 * @param path 文件的本地绝对路径
 * @return
 */
public static String readAsString(String path) {
    try {
        BufferedReader reader = new BufferedReader(new FileReader(path));
        StringBuilder stringBuilder = new StringBuilder();
        String line = null;
        String ls = System.getProperty("line.separator");
        while ((line = reader.readLine()) != null) {
            stringBuilder.append(line);
            stringBuilder.append(ls);
        }
        // 删除最后一个新行分隔符
        stringBuilder.delete(stringBuilder.length() - ls.length(), stringBuilder.length());
        reader.close();

        String content = stringBuilder.toString();
        return content;
    }catch (Exception exception){
        logger.error("readAsString error,path={},exception={}", path, ExceptionUtils.getStackTrace(exception));
        return null;
    }
}
2. 通过BufferedReader和char数组的方式
/**
 * 通过BufferedReader和char数组的方式
 * @param path 文件的本地绝对路径
 * @return
 */
public static String readAsString2(String path) {
    try {
        BufferedReader reader = new BufferedReader(new FileReader(path));
        StringBuilder stringBuilder = new StringBuilder();
        char[] buffer = new char[1024];
        int len = -1;
        while ((len = reader.read(buffer)) != -1) {
            stringBuilder.append(new String(buffer, 0, len));
            buffer = new char[1024];
        }
        reader.close();

        String content = stringBuilder.toString();
        return content;
    }catch (Exception exception){
        logger.error("readAsString2 error,path={},exception={}", path, ExceptionUtils.getStackTrace(exception));
        return null;
    }
}
3. 通过FileInputStream和byte数组
/**
 *  通过FileInputStream和byte数组
 * @param path 文件的本地绝对路径
 * @return
 */
public static String readAsString3(String path) {
    try {
        FileInputStream fis = new FileInputStream(path);
        byte[] buffer = new byte[1024];
        StringBuilder sb = new StringBuilder();
        int len = -1;
        while ((len = fis.read(buffer)) != -1) {
            sb.append(new String(buffer, 0, len));
            buffer = new byte[1024];
        }
        fis.close();

        String content = sb.toString();
        return content;
    }catch (Exception exception){
        logger.error("readAsString3 error,path={},exception={}", path, ExceptionUtils.getStackTrace(exception));
        return null;
    }
}
4. 通过Files的readAllBytes方法
/**
 *  通过Files的readAllBytes方法
 * @param path 文件的本地绝对路径
 * @return
 */
public static String readAsString4(String path) {
    try {
        String content = new String(Files.readAllBytes(Paths.get(path)));
        return content;
    }catch (Exception exception){
        logger.error("readAsString4 error,path={},exception={}", path, ExceptionUtils.getStackTrace(exception));
        return null;
    }
}
5. 通过Scanner类读取
/**
 * 通过Scanner类读取
 * @param path
 * @return
 */
public static String readAsString5(String path) {
    try {
        Scanner scanner = new Scanner(Paths.get(path), StandardCharsets.UTF_8.name());
        String content = scanner.useDelimiter("\\A").next();
        scanner.close();
        return content;
    } catch (Exception exception) {
        logger.error("readAsString5 error,path={},exception={}", path, ExceptionUtils.getStackTrace(exception));
        return null;
    }
}
6.通过Apache Commons IO FileUtils读取

需要先添加maven依赖

<!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.11.0</version>
</dependency>
/**
 * 通过Apache Commons IO FileUtils类读取
 * 需要依赖commons-io包
 *
 * @param path 文件的本地绝对路径
 * @return
 */
public static String readAsString6(String path) {
    try {
        String content = FileUtils.readFileToString(new File(path), StandardCharsets.UTF_8);
        return content;
    } catch (Exception exception) {
        logger.error("readAsString6 error,path={},exception={}", path, ExceptionUtils.getStackTrace(exception));
        return null;
    }
}
7. git仓库

仓库地址:

https://gitee.com/huangchunhua13/hch-tools/blob/master/src/main/java/org/example/util/FileUtil.java
  • 1
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值