Avatar ·

如何将文件内容读取为 Java 字符串?(来自 File、InputStream、Path)

大家好!我是 Java 新手,已经为这个问题折腾了两天。我需要读取一个文本文件(例如 "data.txt")并将其内容作为单个 String 获取。我尝试过 FileReader 和 BufferedReader,但总是在 try-catch 中搞混,代码变得非常庞大。 以下是我写的代码,但它不起作用: ```java File file = new File("data.txt"); String content = ""; try { FileReader reader = new FileReader(file); BufferedReader br = new BufferedReader(reader); String line; while ((line = br.readLine()) != null) { content += line; } br.close(); } catch (IOException e) { e.printStackTrace(); } ``` 问题: 1. 如果文件很大,代码运行得非常慢(我听说在循环中拼接字符串很糟糕)。 2. 需要显式关闭资源,而我经常忘记。 3. 不知道如何正确处理异常——我见过 try-with-resources,但没搞明白。 4. 想要一个通用的方法,能够处理 File、InputStream 和 Path。