需要在项目打包后,生成的jar包所在目录生成一个临时目录。
开始,直接取了user.dir,可打包后发现出不对:user.dir为用户工作目录。
那么只能从class loading入手了,从加载资源class计算URL得到一个该目录(这样能得到结果,就是不知道有什么风险?我在windows和linux上测试过)。
我的FileUtil代码如下:
- public class FileUtil {
- private static final Log logger = LogFactory.getLog(FileUtil.class);
-
-
-
-
-
-
- public static String getJarDir(){
- String path = getDirFromClassLoader();
- if(path == null){
- path = System.getProperty("user.dir");
- }
- return path;
- }
-
-
-
-
-
-
-
-
-
-
-
-
- private static String getDirFromClassLoader(){
- try {
- String path = FileUtil.class.getName().replace(".", "/");
- path ="/"+path+".class";
- URL url=FileUtil.class.getResource(path);
- String jarUrl= url.getPath();
- if(jarUrl.startsWith("file:")){
- if(jarUrl.length()>5){
- jarUrl = jarUrl.substring(5);
- }
- jarUrl = jarUrl.split("!")[0];
-
- }else{
- jarUrl = FileUtil.class.getResource("/").toString().substring(5);
- }
- File file = new File(jarUrl);
- return file.getParent();
-
- } catch (Exception e) {
- }
- return null;
- }
-
-
-
-
-
-
-
-
-
- public static List<String> find(String dir,String suffix){
- List<String> list = new ArrayList<String>();
- try {
- File file = new File(dir);
- if(file.exists() && file.isDirectory()){
- find(file, suffix, list);
- }else{
- throw new IllegalArgumentException("param /"dir/" must be an existing directory .dir = "+dir);
- }
- } catch (Exception e) {
- logger.error("gcw:find(dir,suffix) - "+e.getMessage());
- }
- return list;
- }
-
-
-
-
-
-
- private static void find(File dirFile,String suffix,List<String> list){
- if(dirFile.exists() && dirFile.isDirectory()){
- File[] subFiles = dirFile.listFiles();
- for(File subFile : subFiles) {
- if(subFile.isDirectory()){
- find(subFile, suffix, list);
- }else{
- String path = subFile.getAbsolutePath();
- if(path.endsWith(suffix)){
- list.add(path);
- }
- }
- }
- }else{
- throw new IllegalArgumentException("param /"dir/" must be an existing directory .dir = "+dirFile.getAbsolutePath());
- }
- }
-
- }