staticにファイルアクセスする

毎回ファイルを読むのもなんだなぁということで、static finalにしてしまおう。
元もとのコード(commons-validatorのサンプル)

    InputStream in = null;
    ValidatorResources resources = null;
    
    try {
    
        // Create a new instance of a ValidatorResource, then get a stream
        // handle on the XML file with the actions in it, and initialize the
        // resources from it.  This would normally be done by a servlet
        // run during JSP initialization or some other application-startup
        // routine.
        in = ValidateExample.class.getResourceAsStream("validator-example.xml");
        resources = new ValidatorResources(in);
        
    } finally {
        // Make sure we close the input stream.
        if (in != null) {
            in.close();
        }
    }


修正したもの。

    private static final String VALIDATE_RESOURCE_FILE = "conf/validator/validator-example.xml";
    private static final ValidatorResources resources = getResources();
    private static ValidatorResources getResources(){
        InputStream in = null;
        ValidatorResources resourcess = null;
        
        try {
            in = ClassLoader.class.getResourceAsStream(VALIDATE_RESOURCE_FILE);
            resourcess = new ValidatorResources(in);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return resourcess;
    }


・・・で、いいと思うのだけど。
毎回読むよりかは格段に早いかな?


ところが、これだとJUnitからは動くのだが、Tomcatデバッグしようとするとファイルを読み込めていない。
ここを参考にする。
http://d.hatena.ne.jp/ykhr-kokko/20060914

スレッドからClassLoaderを取ってこれるらしい。

ClassLoader loader = Thread.currentThread().getContextClassLoader();


再度修正。

    private static final String VALIDATE_RESOURCE_FILE = "conf/validator/validator-example.xml";
    private static final ValidatorResources resources = getResources();
    private static ValidatorResources getResources(){
        InputStream in = null;
        ValidatorResources resourcess = null;
        
        try {
            in = Thread.currentThread().getContextClassLoader().getResourceAsStream(VALIDATE_RESOURCE_FILE);
            resourcess = new ValidatorResources(in);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return resourcess;
    }


奥が深いなぁ・・・。