Java中将文件读取为字符串
在Java中将文件读取为字符串有多种方法:
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中。Stream在消耗时才懒惰地填充。
- 文件中的字节会使用指定的字符集解码为字符。
- 返回的Stream包含对打开文件的引用。通过关闭流来关闭文件。
- 在读取过程中不应修改文件内容,否则结果未定义。
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()
方法将文件的所有字节读入一个字节数组中。不要使用此方法来读取大型文件。
此方法确保在读取所有字节或发生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.使用Apache 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的Files
Guava还提供了Files类,可以在一条语句中读取文件内容。
File file = new File("c:/temp/demo.txt"); String content = com.google.common.io.Files.asCharSource(file, Charsets.UTF_8).read();
可以根据您的需求使用上述任何方法将文件读取为字符串。