读取war|jar包中指定的文件
1. 读取war|jar包中指定的文件
获取jar包路径
根据路径加载jar|war
根据相对路径找出文件
1.1 获取jar包路径
public String getPath() {
String classesPath = this.getClass().getClassLoader().getResource("/").getPath();
int index = classesPath.indexOf("!/WEB-INF/classes");
String path = classesPath.substring(0,index);
int prefixIndex = path.indexOf("file:\\");
if(prefixIndex ==0) {
path = path.substring("file:\\".length());
}
return path;
}
1.2 根据流读取流数据
public String getContent(InputStream is) {
String result = null;
InputStreamReader isr = null;
BufferedReader reader = null;
try {
isr = new InputStreamReader(is);
reader = new BufferedReader(isr);
StringBuffer sb = new StringBuffer();
String line;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
result = sb.toString();
} catch (IOException e) {
} finally {
if(reader!=null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(isr!=null) {
try {
isr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return result;
}
1.3 获取流
import java.util.jar.JarFile;
import java.util.zip.ZipEntry;
...
JarFile jar = new JarFile(warPath);
ZipEntry entry = jar.getEntry("menu/ams.json");
InputStream is = jar.getInputStream(entry);
1.4 最终调用
public void test() throws IOException {
String warPath = getWarPath();
JarFile jar = new JarFile(warPath);
ZipEntry entry = jar.getEntry("menu/ams.json");
InputStream is = jar.getInputStream(entry);
String fileContent = getContent(is);
System.out.println(fileContent);
}
1.5 说明
在idea模式下,该模式是不能使用的 因为启动的时候是检测不出jar|war的.
在URL url=this.getClass().getClassLoader().getResource("/");如果是在ide模式下运行的话,执行出来的url 为null. 如果是在java -jar xxx.war 运行模式下,不为null. url.getPath() 为file:/E:/company/02.prject/..../build/libs/xxxx-1.0-SNAPSHOT.war!/WEB-INF/classes!/.
所以可以根据URL url=this.getClass().getClassLoader().getResource("/"); 判断是java -jar xx.war 还是 直接IDE 执行的。
1.IDE执行的话,获取文件就直接用System.getProperty("user.dir")+"/xxx/xxx/xxx/demo.txt"用File 读取文件。
2.java -jar xx.war 就用上面的方式就可以读取到。
ps:我在这边就没用整合2者。
740

被折叠的 条评论
为什么被折叠?



