前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >2018-04-26 Java – Read File to String Examples三种方法把文件读成一个字符串

2018-04-26 Java – Read File to String Examples三种方法把文件读成一个字符串

作者头像
Albert陈凯
发布2018-05-04 12:00:25
1.7K0
发布2018-05-04 12:00:25
举报
文章被收录于专栏:Albert陈凯

原文地址:(英文版) https://howtodoinjava.com/core-java/io/java-read-file-to-string-examples/

Learn to read file to string in java. Examples use Files.readAllBytes, Files.lines and FileReader & BufferedReader to read file content.

学习读取文件,并赋值到String中。 示例使用

  • Files.readAllBytes
  • Files.lines
  • FileReader&BufferedReader 读取文件内容。

Source code of all 3 examples for reading files into string. 三种方法读文件方法的源代码

代码语言:javascript
复制
//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();
}

I have placed a file data.txt at location c:/temp. I will read this file in all 3 examples. 准备一个文件,文件名为data.txt,放到c:/temp目录下面,然后会用三种方法把文件内容读出来

File content in c:/temp/data.txt 文件内容如下

welcome to howtodoinjava.com blog. Learn to grow.

Read File to String using Files.lines() [≥ Java 8]

使用Files.lines()读取文件,需要JDK版本为Java 8 以上

lines() method read all lines from a file to stream and populates lazily as the stream is consumed. Bytes from the file are decoded into characters using the specified charset.

lines()方法从文件中读取所有行,通过流(stream)的方式读到内存。 使用指定的字符集将文件中的二进制字节解码转换为字符。

代码语言:javascript
复制
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.stream.Stream;
 
public class ReadFileToString
{
    public static void main(String[] args)
    {
        String filePath = "c:/temp/data.txt";
 
        System.out.println( readLineByLineJava8( filePath ) );
    }
 
 
    //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();
    }
}

打开你的IDE,COPY下面代码,然后运行,就可以在控制台看到输出

使用Files.readAllBytes()读取文件,需要JDK版本为Java 7 以上

Read File to String using Files.readAllBytes() [≥ Java 7]

readAllBytes() method reads all the bytes from a file. The method ensures that the file is closed when all bytes have been read or an I/O error, or other runtime exception, is thrown.

After reading all bytes, we pass those bytes toStringclass constructor to create a string.

代码语言:javascript
复制
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
 
public class ReadFileToString
{
    public static void main(String[] args)
    {
        String filePath = "c:/temp/data.txt";
 
        System.out.println( readAllBytesJava7( filePath ) );
    }
 
    //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;
    }
}

Read File to String using BufferedReader [< Java 7]

使用BufferedReader 读取文件,最老的方式

If you are still not using java 7 or later, then use BufferedReader class. It’sreadLine()method reads the file one line at a time and return the content.

代码语言:javascript
复制
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
 
public class ReadFileToString
{
    public static void main(String[] args)
    {
        String filePath = "c:/temp/data.txt";
 
        System.out.println( usingBufferedReader( filePath ) );
    }
 
    //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();
    }
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2018.04.26 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 使用Files.lines()读取文件,需要JDK版本为Java 8 以上
  • 使用Files.readAllBytes()读取文件,需要JDK版本为Java 7 以上
  • 使用BufferedReader 读取文件,最老的方式
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档