Java でテキスト ファイルを読み取るさまざまな方法

Java でテキスト ファイルを読み取るさまざまな方法

Java では、データ サイズと使用例に応じて、テキスト ファイルを読み取る方法が複数あります。の java.io そして java.nio.file パッケージ ファイルの読み取りを効率的に処理するためにいくつかのクラスを提供します。一般的なアプローチを 1 つずつ説明しましょう。

1. BufferedReader クラスの使用

バッファリーダー クラスは文字ストリームからテキストを読み取り、効率的に読み取るために文字をバッファリングします。に巻かれていることが多いです。 ファイルリーダー または 入力ストリームリーダー パフォーマンスを向上させるために。

構文

BufferedReader in = new BufferedReader(int サイズのリーダー);



Java
   import     java.io.*  ;   public     class   UsingBufferReader     {      public     static     void     main  (  String  []     args  )     throws     Exception  {          // Creating BufferedReader for Input      BufferedReader     bfri     =     new     BufferedReader  (      new     InputStreamReader  (  System  .  in  ));      System  .  out  .  print  (  'Enter the Path : '  );      // Reading File name      String     path     =     bfri  .  readLine  ();      BufferedReader     bfro      =     new     BufferedReader  (  new     FileReader  (  path  ));      String     st  ;      while     ((  st     =     bfro  .  readLine  ())     !=     null  )      System  .  out  .  println  (  st  );      }   }   


出力

BufferReader の使用出力

2. テキストファイルを読み取るための FileReader クラス

FileReader クラス Java でテキスト ファイルを読み取るために使用されます。ファイルから文字を読み取り、プレーンテキストの読み取りに適しています。このクラスのコンストラクターは、デフォルトの文字エンコーディングとデフォルトのバイト バッファ サイズが適切であることを前提としています。 

このクラスで定義されるコンストラクターは次のとおりです。

  • FileReader(ファイルファイル): 読み取るファイルを指定して新しい FileReader を作成します
  • ファイルリーダー(ファイル記述子 fd): 読み取り元の FileDescriptor を指定して新しい FileReader を作成します
  • FileReader(文字列ファイル名): 読み取るファイルの名前を指定して新しい FileReader を作成します
Java
   import     java.io.*  ;   public     class   UsingFileReader     {      public     static     void     main  (  String  []     args  )     throws     Exception      {      BufferedReader     br     =     new     BufferedReader  (  new     InputStreamReader  (  System  .  in  ));      System  .  out  .  print  (  'Enter the Path : '  );          // Reading File name      String     path     =     br  .  readLine  ();      FileReader     fr     =     new     FileReader  (  path  );      int     i  ;          // Holds true till there is nothing to read      while     ((  i     =     fr  .  read  ())     !=     -  1  )      // Print all the content of a file      System  .  out  .  print  ((  char  )  i  );      }   }   


出力

ファイルリーダーの使用出力

3. テキストファイルを読み取るためのスキャナクラス

スキャナクラス テキスト ファイルを読み取り、プリミティブ型または文字列を解析する簡単な方法を提供します。 正規表現 。区切り文字 (デフォルトでは空白) を使用して、入力をトークンに分割します。

例 1: ループを使用すると

Java
   import     java.io.*  ;   import     java.util.Scanner  ;   public     class   UsingScannerClass      {      public     static     void     main  (  String  []     args  )     throws     Exception      {      BufferedReader     br     =     new     BufferedReader  (  new     InputStreamReader  (  System  .  in  ));      System  .  out  .  print  (  'Enter the Path : '  );          // Reading File name      String     path     =     br  .  readLine  ();          // pass the path to the file as a parameter      File     file     =     new     File  (  path  );          Scanner     sc     =     new     Scanner  (  file  );      while     (  sc  .  hasNextLine  ())      System  .  out  .  println  (  sc  .  nextLine  ());      }   }   


出力

BufferReader の使用出力

例 2: ループを使わずに

Java
   import     java.io.*  ;   import     java.util.Scanner  ;   public     class   ReadingEntireFileWithoutLoop     {      public     static     void     main  (  String  []     args  )      throws     IOException      {      BufferedReader     br     =     new     BufferedReader  (  new     InputStreamReader  (  System  .  in  ));      System  .  out  .  print  (  'Enter the Path : '  );          // Reading File name      String     path     =     br  .  readLine  ();          File     file     =     new     File  (  path  );          Scanner     sc     =     new     Scanner  (  file  );      // we just need to use \Z as delimiter      sc  .  useDelimiter  (  '\Z'  );      System  .  out  .  println  (  sc  .  next  ());      }   }   


出力

ループなしでファイル全体を読み取る出力

4. リスト内のファイル全体を読み取る

次のコマンドを使用して、テキスト ファイル全体をリストに読み込むことができます。 Files.readAllLines() からのメソッド java.nio.file パッケージ 。ファイル内の各行は、リスト内の 1 つの要素になります。

構文

public static List readAllLines(Path pathCharset cs)throws IOException

このメソッドは、次のものを行終端文字として認識します。 

  • u000Du000A -> キャリッジリターン + ラインフィード
  • u000A -> 改行
  • u000D -> キャリッジリターン
Java
   import     java.io.*  ;   import     java.nio.charset.StandardCharsets  ;   import     java.nio.file.*  ;   import     java.util.*  ;   public     class   ReadFileIntoList      {      public     static     List   <  String  >     readFileInList  (  String     fileName  )      {      // Created List of String      List   <  String  >     lines     =     Collections  .  emptyList  ();          try     {      lines     =     Files  .  readAllLines  (      Paths  .  get  (  fileName  )      StandardCharsets  .  UTF_8  );      }     catch  (  IOException     e  )     {      e  .  printStackTrace  ();      }          return     lines  ;      }          public     static     void     main  (  String  []     args  )      throws     IOException      {          BufferedReader     br     =     new      BufferedReader  (  new     InputStreamReader  (  System  .  in  ));      System  .  out  .  print  (  'Enter the Path : '  );          // Reading File name      String     path     =     br  .  readLine  ();          List     l     =     readFileInList  (  path  );          // Iterator iterating over List      Iterator   <  String  >     itr     =     l  .  iterator  ();          while     (  itr  .  hasNext  ())      System  .  out  .  println  (  itr  .  next  ());      }   }   


出力

ReadFileIntoList出力

5. テキストファイルを文字列として読み取る

Java では、テキスト ファイル全体を単一の文字列として読み取ることができます。これは、ファイルの内容を 1 行ずつではなく全体として処理する場合に便利です。

構文:

文字列データ = new String(Files.readAllBytes(Paths.get(fileName)));

例:

Java
   package     io  ;   import     java.nio.file.*  ;   public     class   ReadTextAsString     {      public     static     String     readFileAsString  (  String     fileName  )      throws     Exception      {      String     data     =     ''  ;      data     =     new     String  (      Files  .  readAllBytes  (  Paths  .  get  (  fileName  )));      return     data  ;      }      public     static     void     main  (  String  []     args  )     throws     Exception      {      BufferedReader     br     =     new     BufferedReader  (  new     InputStreamReader  (  System  .  in  ));      System  .  out  .  print  (  'Enter the Path : '  );          // Reading File name      String     path     =     br  .  readLine  ();          String     data     =     readFileAsString  (  path  );          System  .  out  .  println  (  data  );      }   }   

出力

ReadTextAsString出力

クイズの作成

トップ記事

カテゴリ

興味深い記事