1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Javaでファイルを新規作成し処理する。

1
Last updated at Posted at 2022-08-29

結論

全体像は下記のようになります。

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;

public class FileCreateAndProcess {
    public static void main(String[] args) {

        // 1. ファイル取得
        String fileName = "sample.txt";
        String uri = "output/" + fileName;
        Path path = Paths.get(uri);
        File file = new File(uri);

        try {
            // 2. ディレクトリ存在チェック・作成
            Files.createDirectories(path.getParent());

            // 3. ファイルが無ければ新規作成
            if (!file.exists()) {
                Files.createFile(path);
                System.out.println("新規ファイルを作成しました: " + uri);
            } else {
                System.out.println("既存ファイルを使用します: " + uri);
            }

            // 4. 処理(例:データを書き込む)
            Files.write(
                path,
                "処理が実行されました\n".getBytes(StandardCharsets.UTF_8),
                StandardOpenOption.APPEND
            );

        } catch (IOException e) {
            throw new RuntimeException("ファイル処理中にエラーが発生しました", e);
        }
    }
}

流れ

Javaでファイルを新規作成して処理する際の基本的な流れです。
同名のファイルが存在する可能性を考慮しつつ、フォルダが存在しない場合にも対応します。

  1. ファイル取得
  2. ディレクトリ存在チェック・作成
  3. ファイルが無ければ新規作成
  4. 処理

説明

ファイル取得

まず、任意のパスを指定してファイル参照を行います。
File クラスのコンストラクタにパス名を渡し、File オブジェクトを生成します。

    String fileName = "任意のファイル名";
    String uri = "dir/" + fileName;

    Path path = Paths.get(uri);
    File file = new File(uri);

ディレクトリ存在チェック・作成

ファイル保存先となるディレクトリが存在しない場合、Files.createDirectories()
事前に作成しておくと安全です。

    try {
        Files.createDirectories(path.getParent());
    } catch (IOException e) {
        throw new RuntimeException("ディレクトリ作成に失敗しました", e);
    }

ファイル新規作成

ファイルが存在しない場合のみ新規作成を行います。
すでに同名のファイルが存在している場合は新規作成しません。

    if (!file.exists()) {
        try {
            Files.createFile(path);
        } catch (IOException e) {
            throw new RuntimeException("ファイル作成に失敗しました", e);
        }
    }

同名ファイルが存在する状態で createFile を実行すると FileAlreadyExistsException が発生します。
明示的にキャッチして別の処理(例:リネームやスキップ)につなげることも可能です。

処理

新規作成後、または既存ファイルに対して任意の処理を記述します。
テキストファイルの場合は Files.write() を使い、文字コードや追記モードを明示するとより安定します。

    try {
        Files.write(
            path,
            "処理が実行されました\n".getBytes(StandardCharsets.UTF_8),
            StandardOpenOption.APPEND
        );
    } catch (IOException e) {
        throw new RuntimeException("ファイル書き込みに失敗しました", e);
    }

StandardOpenOption.APPEND により追記動作が行われ、
指定しなければ上書き動作 (CREATE + TRUNCATE_EXISTING) になります。


ユースケース例

ログファイルを生成して書き込む場合

処理結果をログとしてファイルへ出力します。ログディレクトリが存在しない場合は自動作成します。

    String fileName = "app.log";
    String uri = "logs/" + fileName;

    Path path = Paths.get(uri);
    File file = new File(uri);

    try {
        Files.createDirectories(path.getParent());
        if (!file.exists()) {
            Files.createFile(path);
        }

        Files.write(
            path,
            "処理が実行されました\n".getBytes(StandardCharsets.UTF_8),
            StandardOpenOption.APPEND
        );
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

既存ファイルがある場合は追記、無い場合は新規作成後に書き込みを行います。
ログ出力内容や日時を簡単に付けたい場合は LocalDateTime を使う方法もあります。

    String message = "[" + LocalDateTime.now() + "] 処理が実行されました\n";

一時ファイルを生成する場合

一時的なデータや中間結果を扱う場合です。
Files.createTempFile() で自動的にユニークなファイル名を生成できます。

    try {
        Path tempFile = Files.createTempFile("sample", ".tmp");
        Files.write(tempFile, "一時データ".getBytes(StandardCharsets.UTF_8));

        System.out.println("一時ファイル: " + tempFile.toAbsolutePath());
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

一時ファイルはシステムのテンポラリ領域に作成されます。
処理終了後に不要になった場合は、Files.delete() で削除できます。

参考文献

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?