目次
主なハイライト
Java でテキスト ファイルを読み取る方法?
方法 1 – BufferedReader クラスを使用する
方法 2 – FileReader クラスを使用する
方法 3 – Scanner クラスを使用する
方法 4 – Files クラス メソッドを使用する
How to Write a Text File in Java?
Method 1 – Using FileWriter Method
Method 2 – Using BufferedWriter Method
Method 3 – Using FileOutputStream Method
Method 4 – Using Files Class
Conclusion
FAQs
Q1. What are the different methods to read a text file in Java?
Q2. What are the different methods for writing a text file in Java?
Q3. What package to use for handling files in Java?
ホームページ Java &#&チュートリアル Javaのテキストファイル

Javaのテキストファイル

Aug 30, 2024 pm 03:54 PM
java

プログラマーは、ファイルの読み取りと書き込みが必要な 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 までご連絡ください。

ホット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ヘンタイを無料で生成します。

ホットツール

メモ帳++7.3.1

メモ帳++7.3.1

使いやすく無料のコードエディター

SublimeText3 中国語版

SublimeText3 中国語版

中国語版、とても使いやすい

ゼンドスタジオ 13.0.1

ゼンドスタジオ 13.0.1

強力な PHP 統合開発環境

ドリームウィーバー CS6

ドリームウィーバー CS6

ビジュアル Web 開発ツール

SublimeText3 Mac版

SublimeText3 Mac版

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

Javaの完全数 Javaの完全数 Aug 30, 2024 pm 04:28 PM

Java における完全数のガイド。ここでは、定義、Java で完全数を確認する方法、コード実装の例について説明します。

Java の乱数ジェネレーター Java の乱数ジェネレーター Aug 30, 2024 pm 04:27 PM

Java の乱数ジェネレーターのガイド。ここでは、Java の関数について例を挙げて説明し、2 つの異なるジェネレーターについて例を挙げて説明します。

ジャワのウェカ ジャワのウェカ Aug 30, 2024 pm 04:28 PM

Java の Weka へのガイド。ここでは、weka java の概要、使い方、プラットフォームの種類、利点について例を交えて説明します。

Javaのスミス番号 Javaのスミス番号 Aug 30, 2024 pm 04:28 PM

Java のスミス番号のガイド。ここでは定義、Java でスミス番号を確認する方法について説明します。コード実装の例。

Java Springのインタビューの質問 Java Springのインタビューの質問 Aug 30, 2024 pm 04:29 PM

この記事では、Java Spring の面接で最もよく聞かれる質問とその詳細な回答をまとめました。面接を突破できるように。

Java 8 Stream Foreachから休憩または戻ってきますか? Java 8 Stream Foreachから休憩または戻ってきますか? Feb 07, 2025 pm 12:09 PM

Java 8は、Stream APIを導入し、データ収集を処理する強力で表現力のある方法を提供します。ただし、ストリームを使用する際の一般的な質問は次のとおりです。 従来のループにより、早期の中断やリターンが可能になりますが、StreamのForeachメソッドはこの方法を直接サポートしていません。この記事では、理由を説明し、ストリーム処理システムに早期終了を実装するための代替方法を調査します。 さらに読み取り:JavaストリームAPIの改善 ストリームを理解してください Foreachメソッドは、ストリーム内の各要素で1つの操作を実行する端末操作です。その設計意図はです

Java での日付までのタイムスタンプ Java での日付までのタイムスタンプ Aug 30, 2024 pm 04:28 PM

Java での日付までのタイムスタンプに関するガイド。ここでは、Java でタイムスタンプを日付に変換する方法とその概要について、例とともに説明します。

カプセルの量を見つけるためのJavaプログラム カプセルの量を見つけるためのJavaプログラム Feb 07, 2025 am 11:37 AM

カプセルは3次元の幾何学的図形で、両端にシリンダーと半球で構成されています。カプセルの体積は、シリンダーの体積と両端に半球の体積を追加することで計算できます。このチュートリアルでは、さまざまな方法を使用して、Javaの特定のカプセルの体積を計算する方法について説明します。 カプセルボリュームフォーミュラ カプセルボリュームの式は次のとおりです。 カプセル体積=円筒形の体積2つの半球体積 で、 R:半球の半径。 H:シリンダーの高さ(半球を除く)。 例1 入力 RADIUS = 5ユニット 高さ= 10単位 出力 ボリューム= 1570.8立方ユニット 説明する 式を使用してボリュームを計算します。 ボリューム=π×R2×H(4

See all articles