首頁 > Java > java教程 > 主體

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

WBOY
發布: 2023-08-30 13:01:06
轉載
1339 人瀏覽過

我們如何在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
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板