Java获取文件

/**
 * 获取文件工具类
 */
public class IOUtils {

    /**
     * 流获取txt文件,传入文件路径,返回字符串
     * @return
     */
    public static String getTxtString(String str){
        // 文件路径
        String filePath = str;
        try {
            String content = new String(Files.readAllBytes(Paths.get(filePath)), StandardCharsets.UTF_8);
            return content;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "获取失败了";
    }

    /**
     * 流获取txt文件,传入文件路径,返回json
     * @return
     */
    public static JsonNode getTxtJson(String str){
        // 将文件转成字符串
        String txtString = getTxtString(str);

        ObjectMapper objectMapper = new ObjectMapper();
        try {
            // 将string转换成json
            JsonNode json = objectMapper.readTree(txtString);
            return json;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

}

猜你喜欢

转载自blog.csdn.net/m0_73505556/article/details/137925209