在Java中,我们有很多方法可以将File转换为String。
文本文件,供以后测试。
c:\\projects\\app.log
A
B
C
D
E
1. Java 11 – Files.readString
在java.nio.file.Files
添加了一个新方法Files.readString
,它使从File中读取字符串变得更加容易。
FileToString1.java
package com.mkyong;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
public class FileToString1 {
public static void main(String[] args) {
String path = "c:\\projects\\app.log";
try {
// default StandardCharsets.UTF_8
String content = Files.readString(Paths.get(path));
System.out.println(content);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Terminal
A
B
C
D
E
2. Java 8 – Files.lines
将文件转换为Stream
并加入。
FileToString2.java
package com.mkyong;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class FileToString2 {
public static void main(String[] args) {
String path = "c:\\projects\\app.log";
try (Stream<String> lines = Files.lines(Paths.get(path))) {
// Formatting like \r\n will be lost
// String content = lines.collect(Collectors.joining());
// UNIX \n, WIndows \r\n
String content = lines.collect(Collectors.joining(System.lineSeparator()));
System.out.println(content);
// File to List
//List<String> list = lines.collect(Collectors.toList());
} catch (IOException e) {
e.printStackTrace();
}
}
}
Terminal
A
B
C
D
E
3. Java 7 – Files.readAllLines
将文件转换为List
FileExample3.java
package com.mkyong;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
public class FileToString3 {
public static void main(String[] args) {
String path = "c:\\projects\\app.log";
try {
// default StandardCharsets.UTF_8
// Java 8
// List<String> content = Files.readAllLines(Paths.get(path));
// Java 7
List<String> content = Files.readAllLines(Paths.get(path), StandardCharsets.UTF_8);
System.out.println(content);
} catch (IOException e) {
e.printStackTrace();
}
}
}
输出量
Terminal
[A, B, C, D, E]
4. Apache Commons IO
pom.xml
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
FileToString4.java
package com.mkyong;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
public class FileToString4 {
public static void main(String[] args) {
String path = "c:\\projects\\app.log";
try {
String content = FileUtils.readFileToString(new File(path), StandardCharsets.UTF_8);
System.out.println(content);
} catch (IOException e) {
e.printStackTrace();
}
}
}
输出量
Terminal
A
B
C
D
E