【发布时间】:2018-09-17 21:48:58
【问题描述】:
我有一个作为产品扩展的 java 程序。我想检查一个文件是否已经改变,如果有就复制它。
我正在使用 ClassLoader 来获取资源,以便获取上次修改日期。我:e
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();
}
}
代码
URL url = this.getClass().getClassLoader().getResource("com/moneydance/modules/features/securityquoteload/resources/stockexchanges.dict");
在代码中返回 null
InputStream input = this.getClass().getClassLoader().getResourceAsStream("com/moneydance/modules/features/securityquoteload/resources/stockexchanges.dict");
返回一个有效的流。他们不应该都工作吗?
【问题讨论】:
-
Hi@Mikerb read this 由 jon skeet 回答。
-
了解更多详情here
-
嗨,我根据 Jon 的 cmets 将 getResource 更改为 ExchangeList.class.getResource("/com/moneydance/modules/features/securityquoteload/resources/stockexchanges.dict")。它也返回了 null。
-
System.out.println(this.getClass().getClassLoader().getClass())打印什么? (我想知道这是否是由于某些自定义类加载器与getResource和getResourceAsStream的实现不一致...) -
嗨@yash 有趣的是,您链接中的文本对于 getResource 和 getResourceAsStream 几乎相同
标签: java classloader