通过java创建jar文件所在的目录

时间:2012-06-23 03:41:42

标签: java path directory

我已经调查了SO的答案,但找不到合适的答案。

当我从jar启动程序时,我需要在jar文件所在的目录中创建一个文件夹。用户保存jar文件的位置无关紧要。

以下是我正在使用的最新代码:System.out.println将打印出正确的目录,但不会创建该文件夹。相比之下,到目前为止,所有内容都保存到我的System32文件夹中。

    public static String getProgramPath() throws IOException{
    String currentdir = System.getProperty("user.dir");
    currentdir = currentdir.replace( "\\", "/" );
    return currentdir;

}

File dir = new File(getProgramPath() + "Comics/");//The name of the directory to create
    dir.mkdir();//Creates the directory

2 个答案:

答案 0 :(得分:3)

获取Jar的路径可能比简单地获取user.dir目录有点棘手。我不记得详细原因,但user.dir在所有情况下都不能可靠地返回此路径。如果你绝对必须得到jar的路径,那么你需要做一点黑魔法并首先得到类的保护域。类似的东西:

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLDecoder;

import javax.swing.JOptionPane;

public class MkDirForMe {
   public static void main(String[] args) {
      try {
         String path = getProgramPath2();

         String fileSeparator = System.getProperty("file.separator");
         String newDir = path + fileSeparator + "newDir2" + fileSeparator;
         JOptionPane.showMessageDialog(null, newDir);

         File file = new File(newDir);
         file.mkdir();
      } catch (IOException e) {
         e.printStackTrace();
      }
   }

   public static String getProgramPath2() throws UnsupportedEncodingException {
      URL url = MkDirForMe.class.getProtectionDomain().getCodeSource().getLocation();
      String jarPath = URLDecoder.decode(url.getFile(), "UTF-8");
      String parentPath = new File(jarPath).getParentFile().getPath();
      return parentPath;
   }
}

即使这不能保证工作,你也不得不让自己辞职,因为当你无法获得Jar的路径时,有一些时候(例如出于安全原因)。 / p>

答案 1 :(得分:1)

通过一些更改(例如在漫画之前添加“/”),我设法创建了您期望的目录。这是我使用的完整代码。

import java.io.*;
public class TestClass {

        public static String getProgramPath() throws IOException{
                String currentdir = System.getProperty("user.dir");
                currentdir = currentdir.replace( "\\", "/" );
                return currentdir;

        }
        public static void main(String[] argv) {
                try {
                        String d = getProgramPath() + "/Comics/";
                        System.out.println("Making directory at " + d);
                        File dir = new File(d);//The name of the directory to create                                                                                      
                        dir.mkdir();//Creates the directory                                                                                                               
                }
                catch (Exception e) { System.out.println("Exception occured" + e);}
        }
}

将来,请不要硬编码“/”之类的东西。使用内置库,这将询问操作系统在这种情况下的正确性。这确保了功能不会(很容易)跨平台。

当然,正确捕获异常等。这只是快速而肮脏的尝试将代码转化为有效的东西。