我們如何在 Java 中從檔案內容建立一個字串?
在 Java 中,你可以使用多種方法讀取檔案的內容,一種方法是使用 java.util.Scanner 類將其讀取到字串中,具體操作如下:
將 Scanner 類例項化,並將其建構函式的引數設定為要讀取的檔案路徑。
建立一個空字串緩衝區。
啟動一個 while 迴圈,條件為 Scanner 是否有下一行。即 while 中的 hasNextLine()。
在迴圈中使用 append() 方法將檔案的每一行附加到 StringBuffer 物件。
使用 toString() 方法將緩衝區內容轉換為字串。
示例
在系統的 C 目錄中建立一個名為 sample.txt 的檔案,複製並貼上以下內容到其中。
Tutorials Point is an E-learning company that set out on its journey to provide knowledge to that class of readers that responds better to online content. With Tutorials Point, you can learn at your own pace, in your own space. After a successful journey of providing the best learning content at tutorialspoint.com, we created our subscription based premium product called Tutorix to provide Simply Easy Learning in the best personalized way for K-12 students, and aspirants of competitive exams like IIT/JEE and NEET.
以下 Java 程式將檔案 sample.txt 中的內容讀入一個字串並打印出來。
import java.io.File; import java.io.IOException; import java.util.Scanner; public class FileToString { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(new File("E://test//sample.txt")); String input; StringBuffer sb = new StringBuffer(); while (sc.hasNextLine()) { input = sc.nextLine(); sb.append(" "+input); } System.out.println("Contents of the file are: "+sb.toString()); } }
輸出
Contents of the file are: Tutorials Point is an E-learning company that set out on its journey to provide knowledge to that class of readers that responds better to online content. With Tutorials Point, you can learn at your own pace, in your own space. After a successful journey of providing the best learning content at tutorialspoint.com, we created our subscription based premium product called Tutorix to provide Simply Easy Learning in the best personalized way for K-12 students, and aspirants of competitive exams like IIT/JEE and NEET.
廣告