三种方法把文件读成一个字符串

节选自:三种方法把文件读成一个字符串


//Example 1
 
//Read file content into string with - Files.lines(Path path, Charset cs)
 
private static String readLineByLineJava8(String filePath)
{
    StringBuilder contentBuilder = new StringBuilder();
    try (Stream<String> stream = Files.lines( 
                                     Paths.get(filePath), StandardCharsets.UTF_8))
    {
        stream.forEach(s -> contentBuilder.append(s).append("\n"));
    }
    catch (IOException e)
    {
        e.printStackTrace();
    }
    return contentBuilder.toString();
}
 
//Example 2
 
//Read file content into string with - Files.readAllBytes(Path path)
 
private static String readAllBytesJava7(String filePath)
{
    String content = "";
    try
    {
        content = new String ( Files.readAllBytes( Paths.get(filePath) ) );
    }
    catch (IOException e)
    {
        e.printStackTrace();
    }
    return content;
}
 
//Example 3
 
//Read file content into string with - using BufferedReader and FileReader
//You can use this if you are still not using Java 8
 
private static String usingBufferedReader(String filePath)
{
    StringBuilder contentBuilder = new StringBuilder();
    try (BufferedReader br = new BufferedReader(new FileReader(filePath)))
    {
 
        String sCurrentLine;
        while ((sCurrentLine = br.readLine()) != null)
        {
            contentBuilder.append(sCurrentLine).append("\n");
        }
    }
    catch (IOException e)
    {
        e.printStackTrace();
    }
    return contentBuilder.toString();
}

发表评论