ホームページ  >  記事  >  Java  >  Java でファイルの内容から文字列を作成するにはどうすればよいでしょうか?

Java でファイルの内容から文字列を作成するにはどうすればよいでしょうか?

WBOY
WBOY転載
2023-08-30 13:01:061299ブラウズ

Java でファイルの内容から文字列を作成するにはどうすればよいでしょうか?

Java では、さまざまな方法でファイルの内容を読み取ることができます。その方法の 1 つは、java.util.Scanner クラスを使用してファイルを文字列として読み取ることです。この場合、

  • Scanner クラスをインスタンス化し、読み取られるファイルのパスをパラメータとしてコンストラクターに渡します。

  • 空の文字列バッファを作成します。

  • スキャナに次の行がある場合は、条件に基づいて while ループを開始します。それは、while の hasNextLine() です。

  • ループ内で append() メソッドを使用します。

  • toString() メソッドを使用して、バッファーの内容を文字列に変換します。

    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 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事はtutorialspoint.comで複製されています。侵害がある場合は、admin@php.cn までご連絡ください。