更新時(shí)間:2022-04-15 09:36:29 來(lái)源:動(dòng)力節(jié)點(diǎn) 瀏覽2894次
Java讀取文件內(nèi)容到字符串有哪些方法呢?動(dòng)力節(jié)點(diǎn)小編來(lái)告訴大家。
使用Java 11中引入的新方法readString(),只需一行就可以將文件的內(nèi)容讀入使用 .StringUTF-8 charset
如果在讀取操作過程中出現(xiàn)任何錯(cuò)誤,此方法可確保文件正確關(guān)閉。
如果OutOfMemoryError文件非常大,例如大于 2GB.
示例 1:將完整文件讀入字符串
Path filePath = Path.of("c:/temp/demo.txt");
String content = Files.readString(fileName);
lines() 方法將文件中的所有行讀取到 Stream 中。當(dāng)流被消費(fèi)時(shí),流被延遲填充。
使用指定的字符集將文件中的字節(jié)解碼為字符。
返回的流包含對(duì)打開文件的引用。通過關(guān)閉流來(lái)關(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[]。不要使用這種方法來(lái)讀取大文件。
此方法確保在讀取所有字節(jié)或引發(fā) I/O 錯(cuò)誤或其他運(yùn)行時(shí)異常時(shí)關(guān)閉文件。讀取所有字節(jié)后,我們將這些字節(jié)傳遞給String類構(gòu)造函數(shù)以創(chuàng)建一個(gè)新字符串。
示例 3:將整個(gè)文件讀取到 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 或更高版本,請(qǐng)使用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庫(kù)提供的實(shí)用程序類。
FileUtils.readFileToString ()是在單個(gè)語(yǔ)句中將整個(gè)文件讀入字符串的絕佳方法。
在單個(gè)語(yǔ)句中讀取文件
File file = new File("c:/temp/demo.txt");
String content = FileUtils.readFileToString(file, "UTF-8");
以上就是關(guān)于“Java讀取文件內(nèi)容到字符串”的介紹,大家如果想了解更多相關(guān)知識(shí),不妨來(lái)關(guān)注一下動(dòng)力節(jié)點(diǎn)的Java在線學(xué)習(xí),里面的課程內(nèi)容從入門到精通,通俗易懂,適合小白學(xué)習(xí),希望對(duì)大家能夠有所幫助。
相關(guān)閱讀
0基礎(chǔ) 0學(xué)費(fèi) 15天面授
有基礎(chǔ) 直達(dá)就業(yè)
業(yè)余時(shí)間 高薪轉(zhuǎn)行
工作1~3年,加薪神器
工作3~5年,晉升架構(gòu)
提交申請(qǐng)后,顧問老師會(huì)電話與您溝通安排學(xué)習(xí)
初級(jí) 202925
初級(jí) 203221
初級(jí) 202629
初級(jí) 203743