更新時間:2022-04-15 09:36:29 來源:動力節(jié)點 瀏覽3380次
Java讀取文件內(nèi)容到字符串有哪些方法呢?動力節(jié)點小編來告訴大家。
使用Java 11中引入的新方法readString(),只需一行就可以將文件的內(nèi)容讀入使用 .StringUTF-8 charset
如果在讀取操作過程中出現(xiàn)任何錯誤,此方法可確保文件正確關(guān)閉。
如果OutOfMemoryError文件非常大,例如大于 2GB.
示例 1:將完整文件讀入字符串
Path filePath = Path.of("c:/temp/demo.txt");
String content = Files.readString(fileName);
lines() 方法將文件中的所有行讀取到 Stream 中。當(dāng)流被消費時,流被延遲填充。
使用指定的字符集將文件中的字節(jié)解碼為字符。
返回的流包含對打開文件的引用。通過關(guān)閉流來關(guān)閉文件。
在讀取過程中不應(yīng)修改文件內(nèi)容,否則結(jié)果未定義。
示例 2:將文件讀入行流
將文件讀取到行流
Path filePath = Path.of("c:/temp/demo.txt");
StringBuilder contentBuilder = new StringBuilder();
try (Stream<String> stream
= Files.lines(Paths.get(filePath), StandardCharsets.UTF_8))
{
//Read the content with Stream
stream.forEach(s -> contentBuilder.append(s).append("\n"));
}
catch (IOException e)
{
e.printStackTrace();
}
String fileContent = contentBuilder.toString();
readAllBytes ()方法將文件中的所有字節(jié)讀入 byte[]。不要使用這種方法來讀取大文件。
此方法確保在讀取所有字節(jié)或引發(fā) I/O 錯誤或其他運行時異常時關(guān)閉文件。讀取所有字節(jié)后,我們將這些字節(jié)傳遞給String類構(gòu)造函數(shù)以創(chuàng)建一個新字符串。
示例 3:將整個文件讀取到 byte[]
讀取文件到字節(jié)數(shù)組
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)
{
e.printStackTrace();
}
如果您仍未使用 Java 7 或更高版本,請使用BufferedReader類。它的readLine()方法一次讀取一行文件并返回內(nèi)容.
示例 4:逐行讀取文件
逐行讀取文件
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();
我們可以使用Apache Commons IO庫提供的實用程序類。
FileUtils.readFileToString ()是在單個語句中將整個文件讀入字符串的絕佳方法。
在單個語句中讀取文件
File file = new File("c:/temp/demo.txt");
String content = FileUtils.readFileToString(file, "UTF-8");
以上就是關(guān)于“Java讀取文件內(nèi)容到字符串”的介紹,大家如果想了解更多相關(guān)知識,不妨來關(guān)注一下動力節(jié)點的Java在線學(xué)習(xí),里面的課程內(nèi)容從入門到精通,通俗易懂,適合小白學(xué)習(xí),希望對大家能夠有所幫助。
相關(guān)閱讀