getResource不起作用,但getResourceAsStream起作用

时间:2018-09-17 12:46:44

标签: java classloader

我有一个Java程序,它是产品的扩展。我希望检查文件是否已更改,然后复制它。

我正在使用ClassLoader来获取资源,因此我可以获取上次修改日期。我:e

range

代码

        boolean copyFile = false;
    String fileName = getRhumbaDirectory()+"\\stockexchanges.dict";
    try {
            File file = new File(fileName);
            Long fileLastModified = file.lastModified();
            URL url = this.getClass().getClassLoader().getResource("com/moneydance/modules/features/securityquoteload/resources/stockexchanges.dict");
            Long resourceLastModified=0L;
            if (url !=null) {
                resourceLastModified = url.openConnection().getLastModified();
            }
            debugInst.debug("ExchangeList", "getData", MRBDebug.INFO, "Modified Date "+fileLastModified+" "+ resourceLastModified);     
            if (resourceLastModified > fileLastModified)
                copyFile = true;
    }
    catch (IOException e){
        copyFile = true;
    }
    if (copyFile) {
        try {
            InputStream input = this.getClass().getClassLoader().getResourceAsStream("com/moneydance/modules/features/securityquoteload/resources/stockexchanges.dict");
            if (input == null) {
                debugInst.debug("ExchangeList", "getData", MRBDebug.INFO, "Problem creating stockexchanges.dict file");     
            }
            else {
                FileOutputStream output = new FileOutputStream(fileName);
                byte [] buffer = new byte[4096];
                int bytesRead = input.read(buffer);
                while (bytesRead != -1) {
                    output.write(buffer, 0, bytesRead);
                    bytesRead = input.read(buffer);
                }
                output.close();
                input.close();
            }
        }
        catch (IOException f) {
            debugInst.debug("ExchangeList", "getData", MRBDebug.DETAILED, "Problem copying default file"+f.getMessage());       
            f.printStackTrace();
        }

    }

在代码

中返回null
                URL url = this.getClass().getClassLoader().getResource("com/moneydance/modules/features/securityquoteload/resources/stockexchanges.dict");

返回有效流。他们俩都不工作吗?

1 个答案:

答案 0 :(得分:0)

感谢“ @Stephen C”,他的建议找到了原因。该论坛是该应用程序专有的,因此无法提供解决方法。