方式1: 使用 BufferedReader
import java.io.*;
import java.nio.charset.StandardCharsets;
public class Demo {
public static void main(String[] args) throws IOException {
String filePath = "/Users/letian/.bashrc";
InputStreamReader inputStreamReader = new InputStreamReader(new FileInputStream(filePath), StandardCharsets.UTF_8);
BufferedReader br = new BufferedReader(inputStreamReader);
try {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append(System.lineSeparator());
line = br.readLine();
}
String content = sb.toString();
System.out.println(content);
} finally {
br.close();
}
}
}
方式2: 使用 Files.readAllLines
代码示例:
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
public class Demo {
public static void main(String[] args) throws IOException {
Path path = Paths.get("/Users/letian/.bashrc");
List<String> lines = Files.readAllLines(path, StandardCharsets.UTF_8);
for (String line : lines) {
System.out.println( line );
}
}
}