inCore JavaJune 18th, 2021 Views
关于如何使用Java Files api将文件内容转换为字符串的快速指南,并附有示例程序。
1.概述
在本教程中,你将学习如何在java中把文件内容转换为字符串。
如果你是java 8的新手,请阅读《如何在java 8中阅读文件》,我们已经展示了逐行阅读文件的不同方法。
Java new Files api有两个有用的方法来读取文件。
readAllLines()
readAllBytes()
让我们写下每个方法的例子,在java中把文件转换成字符串。
2.Java 文件转字符串 - Files.readAllLines()
在下面的示例程序中,首先我们将文件的位置存储在字符串变量中。
接下来,使用Charset.defaultCharset()为文件编码提取默认的字符集。
接下来,调用 ***Files.readAllLines()***方法,输入文件路径。
这个方法返回一个字符串的列表,即 List.
最后,使用java 8 stream api ***collect() 和 join()***方法将List转换为String。
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | package com.javaprogramto.files.tostring;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Collectors;
/**
* Java example to convert File To String.
*
* @author javaprogramto.com
*
*/
public class JavaFilesToString {
public static void main(String[] args) throws IOException {
String filePath = "/CoreJava/src/main/resources/dummy.txt";
Charset encoding = Charset.defaultCharset();
List<String> lines = Files.readAllLines(Paths.get(filePath), encoding);
String string = lines.stream().collect(Collectors.joining("\n"));
System.out.println("file as string ");
System.out.println(string);
}
}
|
输出。
1 2 3 4 5 6 | file as string
Line 1 : Hello Reader
Line 2 : Welcome to the java programt to . com blog
Line 3 : Here you find the articles on the java concepts
Line 4 : This is example to read this file line by line
Line 5 : Let us see the examples on Java 8 Streams API.
|
3.Java 文件到字符串 - Files.readAllBytes()
接下来,调用 Files.readAllBytes() 方法,该方法返回 byte[] 数组作为一个结果。使用String类将字节数组转换为默认编码技术的字符串。
下面的程序产生的输出与第2节中的相同。
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | public class JavaFilesToStringBytes {
public static void main(String[] args) throws IOException {
String filePath = "/Users/venkateshn/Documents/VenkY/blog/workspace/CoreJava/src/main/resources/dummy.txt";
Charset encoding = Charset.defaultCharset();
byte[] bytes = Files.readAllBytes(Paths.get(filePath));
String string = new String(bytes, encoding);
System.out.println("file as string ");
System.out.println(string);
}
}
|
4.结论
在这篇文章中,你已经看到了如何使用java8流方法将文件内容转换为字符串。
GitHub
文件API

(0分,0票)
您需要成为注册会员才能评价这篇文章。 观点鸣叫吧
你想知道如何发展你的技能,成为一名Java Rockstar吗?
请订阅我们的新闻通讯,现在就开始摇滚吧!
为了让您开始,我们免费赠送我们最畅销的电子书!
1.JPA迷你书
2.JVM故障排除指南
3.单元测试的JUnit教程
4.Java注解教程
5.Java面试问题
6.Spring面试问题
7.Android UI设计
以及更多....
