Java
 Computer >> コンピューター >  >> プログラミング >> Java

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


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

  • スキャナーをインスタンス化します コンストラクターへのパラメーターとして、読み取られるファイルのパスを持つクラス。

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

  • スキャナーに次の行がある場合は、条件付きでwhileループを開始します。つまり、 hasNextLine() しばらくの間。

  • ループ内で、 append()を使用して、ファイルの各行をStringBufferオブジェクトに追加します。 メソッド。

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

sample.txtという名前のファイルを作成します システムのCディレクトリで、次のコンテンツをコピーして貼り付けます。

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.

  1. JavaでCSVファイルからデータを読み取る方法は?

    CSV カンマ区切り値の略です 。 CSVファイルでは、各行にカンマ(、)で区切られた単語が含まれています そしてそれは 。csvとともに保存されます 拡張機能。 readLine()を使用して、CSVファイルを1行ずつ読み取ることができます BufferedReaderのメソッド クラス。各行をコンマ文字で分割して、その行の単語を配列に入れます。これで、配列を反復処理するか、適切なインデックスを使用して、配列の内容を簡単に印刷できます。 CSVファイル 例 import java.io.*; public class CSVReaderTest {    p

  2. Javaのプロパティファイルからデータを読み取る方法は?

    プロパティ はHashtableクラスのサブクラスであり、プロパティの永続的なセットを表します。 プロパティ ストリームに保存することも、ストリームからロードすることもできます。プロパティリストの各キーとそれに対応する値は文字列です。 プロパティ ファイルをJavaで使用して、構成を外部化し、キーと値のペアを保存できます。 。 Properties.load()メソッド ofPropertiesクラスはロードに便利です。プロパティ key-valueの形式のファイル ペア 。 構文 public class Properties extends Hashtable credential