java读取文件到字符串

Sometimes while working with files, we need to read the file to String in Java. Today we will look into various ways to read the file to String in Java.

有时在处理文件时,我们需要将文件读取为Java中的String。 今天,我们将研究使用Java将文件读取到String的各种方法。

Java读取文件到字符串 (Java read file to String)

There are many ways to read a file to String in Java. We will explore the following ways in this tutorial.

在Java中,有很多方法可以将文件读取为String。 在本教程中,我们将探索以下方式。

  1. Java read file to String using BufferedReaderJava使用BufferedReader将文件读取为String
  2. Read file to String in java using FileInputStream使用FileInputStream在Java中将文件读取为String
  3. Java read file to string using Files classJava使用Files类将文件读取为字符串
  4. Read file to String using Scanner class使用Scanner类将文件读取到String
  5. Java read file to string using Apache Commons IO FileUtils classJava使用Apache Commons IO FileUtils类将文件读取为字符串

Now let’s look into these classes and read a file to String.

现在,让我们研究这些类,然后将文件读取到String。

Java使用BufferedReader将文件读取为String (Java read file to String using BufferedReader)

We can use BufferedReader readLine method to read a file line by line. All we have to do is append these to a StringBuilder object with newline character. Below is the code snippet to read the file to String using BufferedReader.

我们可以使用BufferedReader readLine方法逐行读取文件。 我们要做的就是将这些附加到带有换行符的StringBuilder对象上。 下面是使用BufferedReader将文件读取为String的代码片段。

BufferedReader reader = new BufferedReader(new FileReader(fileName));
StringBuilder stringBuilder = new StringBuilder();
String line = null;
String ls = System.getProperty("line.separator");
while ((line = reader.readLine()) != null) {stringBuilder.append(line);stringBuilder.append(ls);
}
// delete the last new line separator
stringBuilder.deleteCharAt(stringBuilder.length() - 1);
reader.close();String content = stringBuilder.toString();

There is another efficient way to read file to String using BufferedReader and char array.

还有一种使用BufferedReader和char数组将文件读取到String的有效方法。

BufferedReader reader = new BufferedReader(new FileReader(fileName));
StringBuilder stringBuilder = new StringBuilder();
char[] buffer = new char[10];
while (reader.read(buffer) != -1) {stringBuilder.append(new String(buffer));buffer = new char[10];
}
reader.close();String content = stringBuilder.toString();

使用FileInputStream在Java中将文件读取为String (Read file to String in java using FileInputStream)

We can use FileInputStream and byte array to read file to String. You should use this method to read non-char based files such as image, video etc.

我们可以使用FileInputStream和字节数组将文件读取为String。 您应该使用此方法读取非基于字符的文件,例如图像,视频等。

FileInputStream fis = new FileInputStream(fileName);
byte[] buffer = new byte[10];
StringBuilder sb = new StringBuilder();
while (fis.read(buffer) != -1) {sb.append(new String(buffer));buffer = new byte[10];
}
fis.close();String content = sb.toString();

Java使用Files类将文件读取为字符串 (Java read file to string using Files class)

We can use Files utility class to read all the file content to string in a single line of code.

我们可以使用Files实用程序类将所有文件内容读取为一行代码。

String content = new String(Files.readAllBytes(Paths.get(fileName)));

使用Scanner类将文件读取到String (Read file to String using Scanner class)

The scanner class is a quick way to read a text file to string in java.

扫描程序类是一种将文本文件读取为Java中字符串的快速方法。

Scanner scanner = new Scanner(Paths.get(fileName), StandardCharsets.UTF_8.name());
String content = scanner.useDelimiter("\\A").next();
scanner.close();

Java使用Apache Commons IO FileUtils类将文件读取为字符串 (Java read file to string using Apache Commons IO FileUtils class)

If you are using Apache Commons IO in your project, then this is a simple and quick way to read the file to string in java.

如果您在项目中使用Apache Commons IO,那么这是一种将文件读取为Java中字符串的简单快捷方法。

String content = FileUtils.readFileToString(new File(fileName), StandardCharsets.UTF_8);

Java读取文件到字符串的例子 (Java read file to String example)

Here is the final program with proper exception handling and showing all the different ways to read a file to string.

这是具有适当异常处理的最终程序,该程序显示了将文件读取为字符串的所有不同方式。

package com.journaldev.files;import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Scanner;import org.apache.commons.io.FileUtils;public class JavaReadFileToString {/*** This class shows different ways to read complete file contents to String* * @param args* @throws IOException*/public static void main(String[] args) {String fileName = "/Users/pankaj/Downloads/myfile.txt";String contents = readUsingScanner(fileName);System.out.println("*****Read File to String Using Scanner*****\n" + contents);contents = readUsingApacheCommonsIO(fileName);System.out.println("*****Read File to String Using Apache Commons IO FileUtils*****\n" + contents);contents = readUsingFiles(fileName);System.out.println("*****Read File to String Using Files Class*****\n" + contents);contents = readUsingBufferedReader(fileName);System.out.println("*****Read File to String Using BufferedReader*****\n" + contents);contents = readUsingBufferedReaderCharArray(fileName);System.out.println("*****Read File to String Using BufferedReader and char array*****\n" + contents);contents = readUsingFileInputStream(fileName);System.out.println("*****Read File to String Using FileInputStream*****\n" + contents);}private static String readUsingBufferedReaderCharArray(String fileName) {BufferedReader reader = null;StringBuilder stringBuilder = new StringBuilder();char[] buffer = new char[10];try {reader = new BufferedReader(new FileReader(fileName));while (reader.read(buffer) != -1) {stringBuilder.append(new String(buffer));buffer = new char[10];}} catch (IOException e) {e.printStackTrace();} finally {if (reader != null)try {reader.close();} catch (IOException e) {e.printStackTrace();}}return stringBuilder.toString();}private static String readUsingFileInputStream(String fileName) {FileInputStream fis = null;byte[] buffer = new byte[10];StringBuilder sb = new StringBuilder();try {fis = new FileInputStream(fileName);while (fis.read(buffer) != -1) {sb.append(new String(buffer));buffer = new byte[10];}fis.close();} catch (IOException e) {e.printStackTrace();} finally {if (fis != null)try {fis.close();} catch (IOException e) {e.printStackTrace();}}return sb.toString();}private static String readUsingBufferedReader(String fileName) {BufferedReader reader = null;StringBuilder stringBuilder = new StringBuilder();try {reader = new BufferedReader(new FileReader(fileName));String line = null;String ls = System.getProperty("line.separator");while ((line = reader.readLine()) != null) {stringBuilder.append(line);stringBuilder.append(ls);}// delete the last lsstringBuilder.deleteCharAt(stringBuilder.length() - 1);} catch (IOException e) {e.printStackTrace();} finally {if (reader != null)try {reader.close();} catch (IOException e) {e.printStackTrace();}}return stringBuilder.toString();}private static String readUsingFiles(String fileName) {try {return new String(Files.readAllBytes(Paths.get(fileName)));} catch (IOException e) {e.printStackTrace();return null;}}private static String readUsingApacheCommonsIO(String fileName) {try {return FileUtils.readFileToString(new File(fileName), StandardCharsets.UTF_8);} catch (IOException e) {e.printStackTrace();return null;}}private static String readUsingScanner(String fileName) {Scanner scanner = null;try {scanner = new Scanner(Paths.get(fileName), StandardCharsets.UTF_8.name());// we can use Delimiter regex as "\\A", "\\Z" or "\\z"String data = scanner.useDelimiter("\\A").next();return data;} catch (IOException e) {e.printStackTrace();return null;} finally {if (scanner != null)scanner.close();}}}

You can use any of the above ways to read file content to string in java. However, it’s not advisable if the file size is huge because you might face out of memory errors.

您可以使用上述任何一种方法来将文件内容读取为java中的字符串。 但是,如果文件太大,则不建议这样做,因为您可能会遇到内存不足的错误。

GitHub Repository.GitHub存储库中签出更多Java IO示例。

References:

参考文献:

  • BufferedReader API DocBufferedReader API文档
  • Files API Doc文件API文档

翻译自: https://www.journaldev.com/875/java-read-file-to-string

java读取文件到字符串

java读取文件到字符串_Java读取文件到字符串相关推荐

  1. java读取文件并输出_java读取txt文件并输出结果

    这篇文章主要介绍了java读取txt文件并输出结果,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 描述: 1.java读取指定txt文件并解析 文件 ...

  2. java读取mysql数据库配置文件_java读取properties文件的方法

    Java 读写Properties配置文件 Java 读写Properties配置文件 1.Properties类与Properties配置文件 Properties类继承自Hashtable类并且实 ...

  3. java遍历文件和归类_java读取文件的两种方法:java.io和java.lang.ClassLoader

    java读取文件的两种方法:java.io和java.lang.ClassLoader 什么时候使用java.io,什么时候使用java.lang.ClassLoader呢? (注:要是之前读xml文 ...

  4. java 监听写文件的进度_java读取文件显示进度条的实现方法

    实现这个功能比较简单,用到的类有两个:ProgressMonitorInputStream(主要是整个类) 和 ProgressMonitor ,它们在javax.swing中 大体思路,你要首先知道 ...

  5. java 数据写入txt乱码_java写入文件是乱码

    java写入文件是乱码 我们读取.写入文件流时,经常会遇到乱码的现象,造成乱码的原因当然不可能是一个,这里主要介绍因为文件编码格式而导致的乱码的问题.首先,明确一点,文本文件与二进制文件的概念与差异. ...

  6. java下mysql连接配置文件_Java读取.properties配置文件并连接数据库

    1.读取配置文件 //Properties集合 流对象读取键值对 public static void getNum() throws Exception { Properties p=new Pro ...

  7. java图片上传下载_java实现文件的上传和下载

    1. servlet 如何实现文件的上传和下载? 1.1上传文件 参考自:http://blog.csdn.net/hzc543806053/article/details/7524491 通过前台选 ...

  8. java加载xml配置文件_java读取配置文件的几种方法

    原标题:java读取配置文件的几种方法 在现实工作中,我们常常需要保存一些系统配置信息,大家一般都会选择配置文件来完成,本文根据笔者工作中用到的读取配置文件的方法小小总结一下,主要叙述的是spring ...

  9. java 上文件传示例_Java解压缩文件示例

    java 上文件传示例 Welcome to Java Unzip File Example. In the last post, we learned how to zip file and dir ...

  10. java web 上传附件_JAVA WEB文件上传步骤

    JAVA WEB文件上传步骤如下: 实现 Web 开发中的文件上传功能,两个操作:在 Web 页面添加上传输入项,在 Servlet 中读取上传文件的数据并保存在本地硬盘中. 1.Web 端上传文件. ...

最新文章

  1. 网络工程师转售前的条件
  2. 教你如何提高双目立体视觉系统的精度
  3. .NET中IDisposable接口的基本使用
  4. java字符串编程_java字符串抉择
  5. QLable显示图片 和 QLabel自适应 QLabel 文字居中
  6. GRE词汇乱序版-夹生的词汇2
  7. 行波iq调制器_低功率IQ调制器的基带设计实例—电路精选(1)
  8. 《图解服务器网络架构》 学习笔记
  9. html5如何将4张照片排列,如何将多张图片排列在一张图片呢?学会这两种技巧,轻松搞定...
  10. linux下类似Bus Hound的工具
  11. 插入排序 java实现
  12. java网络编程习题_java练习题-网络编程
  13. AMEsim2019.2的安装和matlab2019的联合仿真
  14. Glide加载长图;WebView加载富文本(图片自适应屏幕大小)
  15. 量子计算(四):量子力学的发展史
  16. v-for中的key
  17. 动态规划求最大工作价值(java实现)
  18. Flink reduce详解
  19. 盘点7款常用的数据分析工具
  20. 哀悼日设置网站主题为黑白主题

热门文章

  1. [SHELL实例] (转)最牛B的 Linux Shell 命令 (一)
  2. SQL Server 2005 正则表达式使模式匹配和数据提取变得更容易
  3. [转载] python中numpy模块的around方法_更好地舍入Python的NumPy.around:舍入numpy的数组
  4. [转载] python中pprint模块详解——print()和pprint()两者的区别
  5. Vue.js 学习笔记 八 v-for
  6. Thread 相关函数和属性
  7. SpringBoot史前简述
  8. Kafka使用经验小结
  9. 用layui实现下拉框select多选,取值
  10. python时间模块time