ホームページ  >  記事  >  Java  >  Javaのテキストファイル

Javaのテキストファイル

WBOY
WBOYオリジナル
2024-08-30 15:54:181195ブラウズ

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