更新時間:2022-04-15 09:36:29 來源:動力節點 瀏覽2866次
Java讀取文件內容到字符串有哪些方法呢?動力節點小編來告訴大家。
使用Java 11中引入的新方法readString(),只需一行就可以將文件的內容讀入使用 .StringUTF-8 charset
如果在讀取操作過程中出現任何錯誤,此方法可確保文件正確關閉。
如果OutOfMemoryError文件非常大,例如大于 2GB.
示例 1:將完整文件讀入字符串
Path filePath = Path.of("c:/temp/demo.txt");
String content = Files.readString(fileName);
lines() 方法將文件中的所有行讀取到 Stream 中。當流被消費時,流被延遲填充。
使用指定的字符集將文件中的字節解碼為字符。
返回的流包含對打開文件的引用。通過關閉流來關閉文件。
在讀取過程中不應修改文件內容,否則結果未定義。
示例 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 ()方法將文件中的所有字節讀入 byte[]。不要使用這種方法來讀取大文件。
此方法確保在讀取所有字節或引發 I/O 錯誤或其他運行時異常時關閉文件。讀取所有字節后,我們將這些字節傳遞給String類構造函數以創建一個新字符串。
示例 3:將整個文件讀取到 byte[]
讀取文件到字節數組
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()方法一次讀取一行文件并返回內容.
示例 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");
以上就是關于“Java讀取文件內容到字符串”的介紹,大家如果想了解更多相關知識,不妨來關注一下動力節點的Java在線學習,里面的課程內容從入門到精通,通俗易懂,適合小白學習,希望對大家能夠有所幫助。
0基礎 0學費 15天面授
有基礎 直達就業
業余時間 高薪轉行
工作1~3年,加薪神器
工作3~5年,晉升架構
提交申請后,顧問老師會電話與您溝通安排學習