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

下面提供两种方式
第一种

在这里插入图片描述

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

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

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

猜你喜欢

转载自blog.csdn.net/taiguolaotu/article/details/112287186
今日推荐