読者です 読者をやめる 読者になる 読者になる

ファイル入出力 Streamクラスでの例

今回はInputStream,OutputStreamクラスのサブクラスでのファイル入出力を紹介します。
Oracle Technology Network for Java Developers | Oracle Technology Network | Oracle
Oracle Technology Network for Java Developers | Oracle Technology Network | Oracleの例です。

[ファイル出力メソッド]

public static void write(String fileName, String data){
    OutputStream out = null;
    try{
        out = new FileOutputStream(fileName);
        out.write(data.getBytes());
    }catch (IOException e) {
        e.printStackTrace();
    }finally{
        if(out != null){
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

[ファイル読込メソッド]

public static String read(String fileName){
    InputStream in = null;
    StringBuffer str = new StringBuffer();
    try{
        in = new FileInputStream(fileName);
        int offset = 0, length = 1024, bufsize = 0;
        byte cbuf[] = new byte[length];
        while((bufsize = in.read(cbuf, offset, length)) != -1){
            str.append(new String(cbuf,offset,bufsize));
            cbuf = new byte[length];
        }
    }catch (IOException e) {
        e.printStackTrace();
    }finally{
        if(in != null){
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return str.toString();
}

つぎに
Oracle Technology Network for Java Developers | Oracle Technology Network | Oracle
Oracle Technology Network for Java Developers | Oracle Technology Network | Oracle
での例を紹介。
[ファイル出力メソッド]

public static void write(String fileName, String data){
    OutputStream out = null;
    try{
        out = new BufferedOutputStream(new FileOutputStream(fileName));
        out.write(data.getBytes());
    }catch (IOException e) {
        e.printStackTrace();
    }finally{
        if(out != null){
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

[ファイル読込メソッド]

public static String read(String fileName){
    InputStream in = null;
    StringBuffer str = new StringBuffer();
    try{
        in = new BufferedInputStream(new FileInputStream(fileName));
        int offset = 0, length = 1024, bufsize = 0;
        byte cbuf[] = new byte[length];
        while((bufsize = in.read(cbuf, offset, length)) != -1){
            str.append(new String(cbuf,offset,bufsize));
            cbuf = new byte[length];
        }
    }catch (IOException e) {
        e.printStackTrace();
    }finally{
        if(in != null){
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return str.toString();
}

■処理速度の違い
FileStream : 299ms.
BufferedStream : 235ms.

地味にバッファ使ったほうが早い。