検索

プログラマーは、ファイルの読み取りと書き込みが必要な Java アプリケーションを操作する際に、Java でテキスト ファイルを使用します。 テキスト ファイルは、情報、コード、その他のデータを保存するための汎用的な方法です。テキスト ファイルは、水平方向に編成された一連の文字とみなされます。 Java のテキスト ファイルには、Java コードを含む .java などの拡張子が付いています。 Java には、プレーン テキスト ファイルからの読み取りまたは書き込みによってプレーン テキスト ファイルを処理できるさまざまなユーティリティが用意されています。理解に応じて、任意の読み取り/書き込みユーティリティを選択できます。

Javaのテキストファイル

主なハイライト

  • テキスト ファイルはさまざまな文字で構成されており、java.io.package を使用して読み取りおよび書き込み操作を実行できます。
  • 読み取るには、Reader クラスまたはユーティリティ クラスを使用できます。ユーティリティ クラスには、File クラス、FileReader、BufferedReader、Scanner クラスなどがあります。
  • Java でファイルに書き込むには、Java 7 Files、FileWriter、BufferedWriter、および FileOutputStream を使用できます。
  • さまざまな方法を使用すると、Java でテキスト ファイルを効率的に処理できます。

Java でテキスト ファイルを読み取る方法?

  • テキスト ファイルでは、各行にプレーン文字が含まれており、各行はその特定の行の終わりを表す目に見えない「行末」記号でマークされます。
  • Java でテキスト ファイルを読み取るには、さまざまなユーティリティが利用可能です。各ユーティリティにはテキスト ファイルから読み取る独自の方法があり、他のユーティリティとは異なるいくつかの機能を提供します。
  • ここでは、理解を深めるために、良い例を使用してさまざまな方法を説明します。

メソッドを開始する前に、パス「/Users/praashibansal/Desktop/Data/test.txt」にあるテキスト ファイル「test.txt」について検討します。内容は「Hello, there」です。

広告 このカテゴリーの人気コース JAVA マスタリー - スペシャライゼーション | 78 コース シリーズ | 15 回の模擬テスト

Javaのテキストファイル

方法 1 – BufferedReader クラスを使用する

  • このメソッドを使用して、文字入力ストリームからテキストを読み取ることができます。デフォルトのバッファ サイズ (8KB) を使用することも、独自のバッファ サイズを指定することもできます。エンコードをサポートしています。
  • 各リクエストには、基礎となる文字ストリームまたはバイト ストリームからの読み取りリクエストを作成するリーダーがあります。
  • そのため、多くの開発者は、read() 操作を使用して任意の Reader に BufferedReader をラップすることを推奨しています。
  • 大きなファイルの処理に適しています。このメソッドは同期されるため、複数のスレッドから使​​用できます。

コード:

import java.io.*;
 public class BReader {
       public static void main(String[] args) throws Exception
    {
              File f = new File(
            "https://cdn.educba.com/Users/praashibansal/Desktop/Data/test.txt");
             // Creating an object
        BufferedReader b
            = new BufferedReader(new FileReader(f));
        // Declaring a string variable
        String s;
        // Condition holds till
        // there is a character in a string
        while ((s = b.readLine()) != null)
            // Print the string
            System.out.println(s);
    }
}

出力:

Javaのテキストファイル

方法 2 – FileReader クラスを使用する

  • FileReader を使用して BufferedReader を取得し、ファイルの読み取りを開始できます。
  • BufferedReader とは異なり、エンコードをサポートせず、代わりにシステムのデフォルトのエンコードを使用します。
  • 文字を読み取る簡単な方法です。
  • このクラスは 3 つのコンストラクターを使用します。
  • FileReader(File file): 新しい FileReader を作成します。ファイルは、コンテンツを読み取るファイルです。
  • FileReader(FileDescriptor fd): FileDescriptor として指定されたファイルから読み取る新しい FileReader を作成します。
  • FileReader(String fileName): fileName という名前のファイルから読み取る新しい FileReader を作成します。

コード:

import java.io.*;
public class RFile {
     public static void main(String[] args) throws Exception
    {
        // Passing the file’s path 
        FileReader f = new FileReader(
            "https://cdn.educba.com/Users/praashibansal/Desktop/Data/test.txt");
        // declaring loop variable
        int i;
             while ((i = f.read()) != -1)
            // Print the content of a file
            System.out.print((char)i);
    }
}

出力:

Javaのテキストファイル

方法 3 – Scanner クラスを使用する

  • これは単純なテキスト スキャナであり、正規表現を介してプリミティブ型と文字列を解析できます。
  • 区切り文字パターンを介して入力をトークンに分割します。デフォルトでは、区切り文字は空白です。
  • その後、トークンはさまざまなタイプの値に変換されます。

コード:

import java.io.File;
import java.util.Scanner;
public class ReadScan
{
  public static void main(String[] args) throws Exception
  {
    // passing the file’s path
    File file = new File("https://cdn.educba.com/Users/praashibansal/Desktop/Data/test.txt");
    Scanner s = new Scanner(file);
    while (s.hasNextLine())
      System.out.println(s.nextLine());
  }
}

出力:

Javaのテキストファイル

方法 4 – Files クラス メソッドを使用する

  • Files クラスは、ファイルの読み取りに次のメソッドを使用します。
  • readAllBytes(Path path): ファイルからすべてのバイトを読み取り、ファイルからのバイトを含むバイト配列を返します。
  • readAllLines(Path path, Charsetcs): ファイルからすべての行を読み取り、ファイルからの行を含むリストを返します。

コード:

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class FCExample {
	public static void main(String[] args) {
		Path path = Paths.get("https://cdn.educba.com/Users/praashibansal/Desktop/Data/test.txt");
		try {
			byte[] b = Files.readAllBytes(path);
			System.out.println("Read bytes: \n"+new String(b));
		} catch (IOException e) {
		}
	}

}

出力:

Javaのテキストファイル

How to Write a Text File in Java?

  • Writing a text file in Java is also a simple process. Java offers different utilities to help write the lines to the file.
  • Now for this process, we are assuming a file at the location- C:\\Users\\Data\\Desktop\\write.txt to which we are writing.

Method 1 – Using FileWriter Method

  • This all-in-one method allows you to write int, byte array, and String to the File.
  • It allows you to write directly into Files and is used in case of the less writes.
  • Using the FileWriter method, you can write part of the String or byte array.

Code:

import java.io.FileWriter; 
 public class FWFile { 
 public static void main(String args[]){ 
 try{ 
 FileWriter f=new FileWriter("https://cdn.educba.com/Users/praashibansal/Desktop/Data/test.txt"); 
 f.write("Hello"); 
 f.close(); 
 }
catch(Exception e)
{
System.out.println(e);
} 
 System.out.println("Hello"); 
 } 
 }

Output:

Javaのテキストファイル

Method 2 – Using BufferedWriter Method

  • BufferedWriter is similar to FileWriter, but BufferedWriter uses an internal buffer to write data into File.
  • It works well if you need to do more write operations and to ensure performance.

Code:

import java.io.FileWriter;
import java.io.BufferedWriter;
import java.io.IOException;

public class BRExample {
  public static void main(String args[]) {
    String data = "data for output file";
    try {
      // Creates a FileWriter
      FileWriter file = new FileWriter("https://cdn.educba.com/Users/praashibansal/Desktop/Data/test.txt");
        try ( // Creates a BufferedWriter
                var o = new BufferedWriter(file)) {
            // Writes the string to the file
            o.write(data);
        }
    }
    catch (IOException e) {
      e.getStackTrace();
    }
  }
}

Output:

Javaのテキストファイル

Method 3 – Using FileOutputStream Method

  • For writing text to the file, you can simply use FileWriter and BufferedWriter.
  • But, if you want the raw stream data to be written directly into a file, it is recommended to use the FileOutputStream utility.
  • With this method, you must create the class object with the specific filename to write data into a file.
  • The following example converts the string content into the byte array we will write into the file using the write() method.

Code:

import java.io.FileOutputStream;
import java.io.IOException;
public class GFG {
       public static void main(String[] args)
    {
        String f = "Hello";
        FileOutputStream o = null;
        // starting Try block 
        try {
            // creating an object of FileOutputStream
            o = new FileOutputStream("https://cdn.educba.com/Users/praashibansal/Desktop/Data/test.txt");
            // storing byte content from string
            byte[] str = f.getBytes();
            // writing into the file
            o.write(str);
            // printing success message 
            System.out.print(
                "data added successfully.");
        }
        // Catch block for exception handling
        catch (IOException e) {
                     System.out.print(e.getMessage());
        }
        finally {
            // closing the object
            if (o != null) {
                // checking if the file is closed 
                       try {
                                                       o.close();
                }
                catch (IOException e) {
                    // showing exception message
                    System.out.print(e.getMessage());
                }
            }
        }
    }
}

Output:

Javaのテキストファイル

Method 4 – Using Files Class

  • In Java 7, you will get another utility, Files class, allowing you to write to a text file using its write function.
  • Internally, this class uses the OutputStream utility to write a byte array into the file.

Code:

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
/**
 * Java Files write file example
 * 
 * @author pankaj
 *
 */
public class FCExample {
	public static void main(String[] args) {
		Path path = Paths.get("https://cdn.educba.com/Users/praashibansal/Desktop/Data/test.txt");
		try {
			String str = "Example";
			byte[] bs = str.getBytes();
			Path w = Files.write(path, bs);
			System.out.println("Written content in file:\n"+ new String(Files.readAllBytes(w)));
		} catch (IOException e) {
		}
	}
}

Output:

Javaのテキストファイル

Conclusion

Reading and writing a file in Java is a straightforward process. With the availability of different methods and utilities in Java, you can choose a specific way to read from and write to a file. Each utility has its functionality that makes it different from others.

FAQs

Q1. What are the different methods to read a text file in Java?

Answer: To read, you can use Reader Class or utility class. Some utility classes are- File Class, FileReader, BufferedReader, and Scanner class.

Q2. What are the different methods for writing a text file in Java?

Answer: To write a file in Java, you can use FileWriter, BufferedWriter, java 7 Files, FileOutputStream, and many other methods.

Q3. What package to use for handling files in Java?

Answer: You can easily import the File class from the java.io package to work with files.

以上がJavaのテキストファイルの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
高度なJavaプロジェクト管理、自動化の構築、依存関係の解像度にMavenまたはGradleを使用するにはどうすればよいですか?高度なJavaプロジェクト管理、自動化の構築、依存関係の解像度にMavenまたはGradleを使用するにはどうすればよいですか?Mar 17, 2025 pm 05:46 PM

この記事では、Javaプロジェクト管理、自動化の構築、依存関係の解像度にMavenとGradleを使用して、アプローチと最適化戦略を比較して説明します。

適切なバージョン化と依存関係管理を備えたカスタムJavaライブラリ(JARファイル)を作成および使用するにはどうすればよいですか?適切なバージョン化と依存関係管理を備えたカスタムJavaライブラリ(JARファイル)を作成および使用するにはどうすればよいですか?Mar 17, 2025 pm 05:45 PM

この記事では、MavenやGradleなどのツールを使用して、適切なバージョン化と依存関係管理を使用して、カスタムJavaライブラリ(JARファイル)の作成と使用について説明します。

カフェインやグアバキャッシュなどのライブラリを使用して、Javaアプリケーションにマルチレベルキャッシュを実装するにはどうすればよいですか?カフェインやグアバキャッシュなどのライブラリを使用して、Javaアプリケーションにマルチレベルキャッシュを実装するにはどうすればよいですか?Mar 17, 2025 pm 05:44 PM

この記事では、カフェインとグアバキャッシュを使用してJavaでマルチレベルキャッシュを実装してアプリケーションのパフォーマンスを向上させています。セットアップ、統合、パフォーマンスの利点をカバーし、構成と立ち退きポリシー管理Best Pra

キャッシュや怠zyなロードなどの高度な機能を備えたオブジェクトリレーショナルマッピングにJPA(Java Persistence API)を使用するにはどうすればよいですか?キャッシュや怠zyなロードなどの高度な機能を備えたオブジェクトリレーショナルマッピングにJPA(Java Persistence API)を使用するにはどうすればよいですか?Mar 17, 2025 pm 05:43 PM

この記事では、キャッシュや怠zyなロードなどの高度な機能を備えたオブジェクトリレーショナルマッピングにJPAを使用することについて説明します。潜在的な落とし穴を強調しながら、パフォーマンスを最適化するためのセットアップ、エンティティマッピング、およびベストプラクティスをカバーしています。[159文字]

Javaのクラスロードメカニズムは、さまざまなクラスローダーやその委任モデルを含むどのように機能しますか?Javaのクラスロードメカニズムは、さまざまなクラスローダーやその委任モデルを含むどのように機能しますか?Mar 17, 2025 pm 05:35 PM

Javaのクラスロードには、ブートストラップ、拡張機能、およびアプリケーションクラスローダーを備えた階層システムを使用して、クラスの読み込み、リンク、および初期化が含まれます。親の委任モデルは、コアクラスが最初にロードされ、カスタムクラスのLOAに影響を与えることを保証します

See all articles

ホットAIツール

Undresser.AI Undress

Undresser.AI Undress

リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover

AI Clothes Remover

写真から衣服を削除するオンライン AI ツール。

Undress AI Tool

Undress AI Tool

脱衣画像を無料で

Clothoff.io

Clothoff.io

AI衣類リムーバー

AI Hentai Generator

AI Hentai Generator

AIヘンタイを無料で生成します。

ホットツール

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser は、オンライン試験を安全に受験するための安全なブラウザ環境です。このソフトウェアは、あらゆるコンピュータを安全なワークステーションに変えます。あらゆるユーティリティへのアクセスを制御し、学生が無許可のリソースを使用するのを防ぎます。

MantisBT

MantisBT

Mantis は、製品の欠陥追跡を支援するために設計された、導入が簡単な Web ベースの欠陥追跡ツールです。 PHP、MySQL、Web サーバーが必要です。デモおよびホスティング サービスをチェックしてください。

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Eclipse を SAP NetWeaver アプリケーション サーバーと統合します。

SublimeText3 英語版

SublimeText3 英語版

推奨: Win バージョン、コードプロンプトをサポート!

SublimeText3 Mac版

SublimeText3 Mac版

神レベルのコード編集ソフト(SublimeText3)