文
章
目
录
章
目
录
在Java中学习如何将文本文件读取为字符串。以下示例使用Files.readAllBytes()、Files.lines()(逐行读取)以及FileReader和BufferedReader来将文件读取为字符串。
1.使用Files.readString() – Java 11
在Java 11中引入的新方法readString() 只需一行代码即可使用UTF-8字符集将文件内容读取为字符串。
- 如果在读取操作期间出现任何错误,此方法会确保文件被正确关闭。
- 如果文件非常大,例如大于2GB,则会抛出OutOfMemoryError。
Path filePath = Path.of("c:/temp/demo.txt");
String content = Files.readString(fileName);
2.使用Files.lines() – Java 8
lines ()方法将文件中的所有行读取到Stream中。当流被消耗时,流被延迟填充。
- 使用指定的字符集将文件中的字节解码为字符。
- 返回的流包含对打开文件的引用。通过关闭流来关闭文件。
- 读取过程中不要修改文件内容,否则结果是undefined。
//将文件读取到lines流
Path filePath = Path.of("c:/temp/demo.txt");
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) {
//handle exception
}
String fileContent = contentBuilder.toString();
3. 使用Files.readAllBytes() – Java 7
readAllBytes()方法将文件中的所有字节读取到 byte[] 中。不要使用此方法读取大文件。
此方法可确保在读取所有字节或引发 I/O 错误或其他运行时异常时关闭文件。读取所有字节后,我们将这些字节传递给String
类构造函数以创建一个新的字符串。
//将文件读取到字节数组
Path filePath = Path.of("c:/temp/demo.txt");
String fileContent = "";
try {
byte[] bytes = Files.readAllBytes(Paths.get(filePath));
fileContent = new String (bytes);
} catch (IOException e) {
//handle exception
}
4. 使用BufferedReader – Java 6
如果您仍然不使用 Java 7 或更高版本,请使用BufferedReader类。它的readLine()
方法一次读取文件一行并返回内容.
//逐行读取文件
Path filePath = Path.of("c:/temp/demo.txt");
String fileContent = "";
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();
}
fileContent = contentBuilder.toString();
5. Commons IO 的FileUtils
我们可以使用Apache Commons IO库提供的实用程序类。FileUtils.readFileToString ()是在单个语句中将整个文件读入字符串的绝佳方法。
//在单个语句中读取文件
File file = new File("c:/temp/demo.txt");
String content = FileUtils.readFileToString(file, "UTF-8");
6.Guava 的文件
Guava 还提供了Files类,可用于在单个语句中读取文件内容。
//在单个语句中读取文件
File file = new File("c:/temp/demo.txt");
String content = com.google.common.io.Files.asCharSource(file, Charsets.UTF_8).read();
使用上面给出的任何方法通过 Java 将文件读入字符串。