首頁 >Java >java教程 >我們如何在Java中從文件內容建立一個字串?

我們如何在Java中從文件內容建立一個字串?

WBOY
WBOY轉載
2023-08-30 13:01:061356瀏覽

我們如何在Java中從文件內容建立一個字串?

在Java 中,您可以透過多種方式讀取檔案的內容,其中一種方法是使用java.util.Scanner 類別將其讀取為字串,為此,

  • 實例化Scanner 類,並將要讀取的檔案的路徑作為其建構函數的參數。

  • 建立一個空字串緩衝區。

  • 如果掃描器有下一行,則根據條件啟動 while 迴圈。即 hasNextLine() at while。

  • 在迴圈內使用 append() 方法。

  • 使用 toString() 方法將緩衝區內容轉換為 String。

    li>

範例

在系統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.

以上是我們如何在Java中從文件內容建立一個字串?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除