Java でテキスト ファイルを読み書きする方法は複数あります。これは、多くのアプリケーションを処理するときに必要になります。 Java でプレーン テキスト ファイルを読み取る方法はいくつかあります。 FileReader、BufferedReader、または Scanner を使用してテキスト ファイルを読み取ることができます。すべてのユーティリティは何か特別なものを提供します。 BufferedReader は高速読み取りのためのデータのバッファリングを提供し、Scanner は解析機能を提供します。
方法:
- 使用する BufferedReader クラス
- 使用する スキャナクラス
- ファイルリーダークラスの使用
- リスト内のファイル全体を読み取る
- テキストファイルを文字列として読み取る
また、BufferReader と Scanner の両方を使用して、Java でテキスト ファイルを 1 行ずつ読み取ることもできます。次に、Java SE 8 では別の Stream クラスが導入されます。 java.util.stream.Stream これは、ファイルを読み取るための遅延的でより効率的な方法を提供します。
ヒントノート: ストリームのフラッシュ/クローズ、例外処理などの優れたコードを記述する習慣は、初心者によるコードの理解を深めるために避けられてきました。
上記の各メソッドについて、最も重要なこととして、クリーンな Java プログラムを介して実装することによって、さらに詳しく説明します。
1. テキストファイルを読み取るためのBufferedReaderクラス
このメソッドは、文字入力ストリームからテキストを読み取ります。文字、配列、行を効率的に読み取るためにバッファーを実行します。バッファ サイズを指定することも、デフォルト サイズを使用することもできます。デフォルトは、ほとんどの目的に十分な大きさです。一般に、Reader から行われる各読み取りリクエストにより、基礎となる文字またはバイト ストリームに対して対応する読み取りリクエストが行われます。したがって、次に示すように、FileReaders や InputStreamReaders など、read() 操作にコストがかかる可能性がある Reader の周囲に BufferedReader をラップすることをお勧めします。
構文
BufferedReader in = new BufferedReader(Reader in, int size);>
例
ジャワ
文字列をJavaに変換する
// Java Program to illustrate Reading from FileReader> // using BufferedReader Class> // Importing input output classes> import> java.io.*;> // Main class> public> class> GFG {> > // main driver method> > public> static> void> main(String[] args)> throws> Exception> > {> > // File path is passed as parameter> > File file => new> File(> > 'C:UserspankajDesktop est.txt'> );> > // Note: Double backquote is to avoid compiler> > // interpret words> > // like est as (ie. as a escape sequence)> > // Creating an object of BufferedReader class> > BufferedReader br> > => new> BufferedReader(> new> FileReader(file));> > // Declaring a string variable> > String st;> > // Condition holds true till> > // there is character in a string> > while> ((st = br.readLine()) !=> null> )> > // Print the string> > System.out.println(st);> > }> }> |
>
>
出力
If you want to code refer to techcodeview.com>
2. テキストファイルを読み取るための FileReader クラス
文字ファイルを読み取るための便利なクラス。このクラスのコンストラクターは、デフォルトの文字エンコーディングとデフォルトのバイト バッファ サイズが適切であることを前提としています。
このクラスで定義されるコンストラクターは次のとおりです。
- FileReader(File file): 読み取るファイルを指定して、新しい FileReader を作成します。 FileReader(FileDescriptor fd): 読み取るファイルDescriptor を指定して、新しい FileReader を作成します。 FileReader(String fileName): ファイルの名前を指定して、新しい FileReader を作成します。読み取るファイル
例
ジャワ
// Java Program to Illustrate reading from> // FileReader using FileReader class> // Importing input output classes> import> java.io.*;> // Main class> // ReadingFromFile> public> class> GFG {> > // Main driver method> > public> static> void> main(String[] args)> throws> Exception> > {> > // Passing the path to the file as a parameter> > FileReader fr => new> FileReader(> > 'C:UserspankajDesktop est.txt'> );> > // Declaring loop variable> > 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);> > }> }> |
>
>
ひどいとは何ですか
出力
If you want to code refer to techcodeview.com>
3. テキストファイルを読み取るためのスキャナクラス
正規表現を使用してプリミティブ型と文字列を解析できるシンプルなテキスト スキャナー。スキャナは、デフォルトで空白と一致する区切り文字パターンを使用して入力をトークンに分割します。結果として得られるトークンは、さまざまな次のメソッドを使用してさまざまなタイプの値に変換できます。
例 1: ループを使用すると
ジャワ
// Java Program to illustrate> // reading from Text File> // using Scanner Class> import> java.io.File;> import> java.util.Scanner;> public> class> ReadFromFileUsingScanner {> > public> static> void> main(String[] args)> throws> Exception> > {> > // pass the path to the file as a parameter> > File file => new> File(> > 'C:UserspankajDesktop est.txt'> );> > Scanner sc => new> Scanner(file);> > while> (sc.hasNextLine())> > System.out.println(sc.nextLine());> > }> }> |
>
>
出力
If you want to code refer to techcodeview.com>
例 2: ループを使わずに
ジャワ
// Java Program to illustrate reading from FileReader> // using Scanner Class reading entire File> // without using loop> import> java.io.File;> import> java.io.FileNotFoundException;> import> java.util.Scanner;> public> class> ReadingEntireFileWithoutLoop {> > public> static> void> main(String[] args)> > throws> FileNotFoundException> > {> > File file => new> File(> > 'C:UserspankajDesktop est.txt'> );> > Scanner sc => new> Scanner(file);> > // we just need to use as delimiter> > sc.useDelimiter(> ''> );> > System.out.println(sc.next());> > }> }> |
>
>
出力
If you want to code refer to techcodeview.com>
4. リスト内のファイル全体を読み取る
ファイルからすべての行を読み取ります。このメソッドにより、すべてのバイトが読み取られるか、I/O エラーまたはその他のランタイム例外がスローされたときに、ファイルが確実に閉じられます。ファイルのバイトは、指定された文字セットを使用して文字にデコードされます。
窓を開く
構文:
public static List readAllLines(Path path,Charset cs)throws IOException>
このメソッドは、次のものを行終端文字として認識します。
u000D followed by u000A, CARRIAGE RETURN followed by LINE FEED u000A, LINE FEED u000D, CARRIAGE RETURN>
例
ジャワ
// Java program to illustrate reading data from file> // using nio.File> import> java.io.*;> import> java.nio.charset.StandardCharsets;> import> java.nio.file.*;> import> java.util.*;> public> class> ReadFileIntoList {> > public> static> List> > readFileInList(String fileName)> > {> > List lines = Collections.emptyList();> > try> {> > lines = Files.readAllLines(> > Paths.get(fileName),> > StandardCharsets.UTF_8);> > }> > catch> (IOException e) {> > // do something> > e.printStackTrace();> > }> > return> lines;> > }> > public> static> void> main(String[] args)> > {> > List l = readFileInList(> > 'C:UserspankajDesktop est.java'> );> > Iterator itr = l.iterator();> > while> (itr.hasNext())> > System.out.println(itr.next());> > }> }> |
>
反復マップJava
>
出力
If you want to code refer to techcodeview.com>
5. テキストファイルを文字列として読み取る
例
ジャワ
// Java Program to illustrate> // reading from text file> // as string in 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> > {> > String data = readFileAsString(> > 'C:UserspankajDesktop est.java'> );> > System.out.println(data);> > }> }> |
>
>
出力
If you want to code refer to techcodeview.com>