关闭

java读文件

别叨叨 1年前 ⋅ 105 阅读
public class ReadFileUtils {
    
    /**
     * 读取文件
     *
     * @param path    文件路径
     * @param ordered 是否有序(无序效率较高)
     * @return
     */
    public static String readFile(String path, Boolean ordered) {
        Stream<String> stream = null;
        try {
            stream = Files.lines(Paths.get(path));
        } catch (IOException e) {
            e.printStackTrace();
        }
        StringBuilder stringBuilder = new StringBuilder();
        if (ordered) {
            //有序
            stream.forEachOrdered(action -> {
                stringBuilder.append(action).append("\n");
            });
        } else {
            //无序
            stream.forEach(action -> {
                stringBuilder.append(action).append("\n");
            });
        }
        return stringBuilder.toString();
    }

    /**
     * 通过File.readAllLines读取文件
     *
     * @param path 文件路径
     * @return
     */
    public static String readFileAllLines(String path) {
        List<String> list = null;
        try {
            list = Files.readAllLines(Paths.get(path),
                    StandardCharsets.UTF_8);
        } catch (IOException e) {
            e.printStackTrace();
        }
        StringBuilder stringBuilder = new StringBuilder();
        list.forEach(action -> stringBuilder.append(action).append("\n"));
        return stringBuilder.toString();
    }

    /**
     * 通过BufferedReader读取文件
     *
     * @param path 文件路径
     * @return
     */
    public static String readFileByBufferedReader(String path) {
        StringBuilder stringBuilder = new StringBuilder();
        try (BufferedReader bufferedReader = Files.newBufferedReader(Paths.get(path))) {
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                stringBuilder.append(line).append("\n");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return stringBuilder.toString();
    }
}

全部评论: 0

    我有话说: