ファイル入出力 - 最適解?

Javaにはファイル入出力のためにクラスが用意されているが、一番安定して使えそうなのは

  • java.io.OutputStreamWriter
  • java.io.InputStreamReader

じゃないかと思う。

ファイル出力処理を書いてみた。
# 中で独自クラスLogUtilやEncodeCharsetなどを使っているがそちらはまたのちほど書こうと思う。

/**
 * ファイル出力.
 * ディレクトリが存在しない場合は作成する.
 * @param outPath 出力パス
 * @param data 出力文字列
 * @param append 追記モードフラグ
 * @param charset エンコード
 * @throws IOException
 */
public static void writeFile(String outPath, String data, boolean append, EncodeCharset charset) throws IOException{
    OutputStreamWriter writer = null;
    try{
        makedirParent(outPath);

        writer = new OutputStreamWriter(new FileOutputStream(outPath, append), charset.getValue());
        writer.write(data);
    }catch (IOException e) {
        LogUtil.error("ファイル出力に失敗", e);
        throw e;
    }finally{
        if(writer != null){
            try{
                writer.close();
            }catch (IOException e) {
                LogUtil.error("closeに失敗", e);
                throw e;
            }
        }
    }
}

ついでにディレクトリ作成するメソッドも作ってみた。
ファイル出力先までディレクトリがなかったらExceptionが発生するからね!

/**
 * ディレクトリを作成する.
 * @param dirPath
 */
public static void makedir(String dirPath){
    File dir = new File(dirPath);
    if(!dir.exists()){
        dir.mkdirs();
    }
}

ファイルパスから親ディレクトリを用意するメソッド

/**
 * ファイルの親ディレクトリを作成する.
 * @param filePath
 */
public static void makedirParent(String filePath){
    File file = new File(filePath);
    makedir(file.getParent());
}