Java讀取文件為字符串方法
方法一:使用Files工具類
-
java.nio.file.Files
工具類,不依賴三方組件 -
Path.of
方法在jdk11才支持
public String fileToString(String path) throws IOException {
return Files.readString(Path.of(path));
}
方法二:使用字符流FileReader
public String fileToString2(String path) throws IOException {
FileReader reader = new FileReader(new File(path));
StringBuilder stringBuilder = new StringBuilder();
char[] buffer = new char[10];
int size;
while ((size = reader.read(buffer)) != -1) {
stringBuilder.append(buffer, 0, size);
}
return stringBuilder.toString();
}
常見字符流和字節(jié)流文章來源地址http://www.zghlxwxcb.cn/news/detail-429450.html
方法三:使用Apache的Commons Io組件工具類
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.11.0</version>
</dependency>
public String fileToString(String path) throws IOException {
return FileUtils.readFileToString(new File(path), StandardCharsets.UTF_8);
}
文章來源:http://www.zghlxwxcb.cn/news/detail-429450.html
到了這里,關(guān)于Java讀取文件為字符串方法的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!