java根据路径去获取路径中的文件的内容

该博客展示了在Java中读取文件的两种方法:一种使用BufferedReader,另一种使用Files.readAllBytes。代码示例详细解释了每种方法的实现过程,强调了它们在处理文件内容时的实用性。
摘要由CSDN通过智能技术生成

下面提供两种方式
第一种

在这里插入图片描述

public static void main(String[] args) throws IOException {

        String fullFilePath = "C:\\Users\\yangquan\\Desktop\\book\\1.html";
        String txt = readFileByPath(fullFilePath);
        System.out.println(txt);

    }

    public static String readFileByPath(String fullFilePath) throws IOException {
        StringBuilder result = new StringBuilder();
        try {
            File file = new File(fullFilePath);
            FileInputStream fileInputStream = new FileInputStream(file);
            InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, "UTF-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String line = null;
            while ((line = bufferedReader.readLine()) != null) {
                result.append(line);
            }
            bufferedReader.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result.toString();
    }

在这里插入图片描述
第二种方式比较简单

 public static void main(String[] args) throws IOException {

        String fullFilePath = "C:\\Users\\yangquan\\Desktop\\book\\1.html";
        String txt = readFileByPath(fullFilePath);
        System.out.println(txt);

    }

    public static String readFileByPath(String fullFilePath) throws IOException {
        byte[] content = Files.readAllBytes(Paths.get(fullFilePath));
        return (new String(content));
    }

在这里插入图片描述
也是同样可以获取到

这辈子坚持与不坚持都不可怕,怕的是独自走在坚持的道路上!!!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值