Java InputStreamをFileに変換する基本と実践

InputStreamをFileに変換する方法は以下の通りです:

import java.io.*;

public class Main {
    public static void main(String[] args) {
        InputStream inputStream = null;
        FileOutputStream fileOutputStream = null;
        try {
            inputStream = new FileInputStream("input.txt");
            File file = new File("output.txt");
            fileOutputStream = new FileOutputStream(file);

            byte[] buffer = new byte[1024];
            int length;
            while ((length = inputStream.read(buffer)) != -1) {
                fileOutputStream.write(buffer, 0, length);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
                if (fileOutputStream != null) {
                    fileOutputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

このコードのセクションは、まずファイルの内容を読み取るためにInputStreamのオブジェクトを作成し、その後、内容を書き込むためにFileのオブジェクトを作成します。InputStreamの内容を読み取り、それをFileに書き込むことで、InputStreamをFileに変換する機能が実現されています。

bannerAds