InputStreamオブジェクトにあるデータをファイルに出力

2009/02/16 18:07Update
TAGS: InputStream | ファイル | File | サンプル

InputStreamオブジェクトからファイルに出力するためのサンプルです。

サンプル
package com.test.io;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

//InputStreamオブジェクト -> Fileに出力するサンプル
public class TestJavaIO {

    public static void main(String[] args) {
        try {
            //InputStreamオブジェクト
            InputStream bais = new ByteArrayInputStream("Hello".getBytes());
            
            //ファイル
            File file = new File("c:\\hello.txt");
            
            //InputStreamオブジェクトにあるデータをc:\\hello.txtに出力
            createFileWithInputStream(bais, file);
            
            //その結果、c:\に中身は"Hello"のhello.txtファイルが生成されます
        } catch(IOException e) {
            e.printStackTrace();
        }
    }
    
    //InputStreamオブジェクトにあるデータをファイルに出力する
    static void createFileWithInputStream(InputStream inputStream, File destFile) throws IOException {

        byte[] buffer = new byte[1024];
        int length = 0;
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(destFile);

            while ((length = inputStream.read(buffer)) >= 0) {
                fos.write(buffer, 0, length);
            }

            fos.close();
            fos = null;
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                }
            }
        }
    }
}


createFileWithInputStreamメソッド:肝心な実装部分です。
mainメソッド:使い方例

有关作者
Syboos.jp編集長AJavaやオープンソース情報の執筆、Webサイトの開発や運営全般の業務に携わる。

Sponsored Link


Comments

用户名 (required)

Email (will not be published) (required)

URL

Evaluation