相关文章:
-
常规方法
private static String printFileContent1(String path) { InputStream is = null; StringBuilder builder = new StringBuilder(); try { is = new FileInputStream(path); int length; byte[] data = new byte[1<<10]; while ((length = is.read(data)) != -1) { builder.append(new String(data, 0, length)); } } catch (IOException e) { e.printStackTrace(); } finally { if (is != null) { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } } return builder.toString(); } public static void main(String[] args) { String path = "C:\\Users\\XJ\\Desktop\\Java.txt"; System.out.println(printFileContent1(path)); } // Hello World ! // Hello Java !
-
lambda 方法
private static String printFileContent2(String path) { StringBuilder builder = new StringBuilder(); try { Files.readAllLines(Paths.get(path)) .forEach(str -> builder.append(str).append("\n")); } catch (IOException e) { e.printStackTrace(); } return builder.toString(); } public static void main(String[] args) { String path = "C:\\Users\\XJ\\Desktop\\Java.txt"; System.out.println(printFileContent2(path)); } // Hello World ! // Hello Java !