繁体   English   中英

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

[英]Creating a directory wherever jar file is located through java

我已经调查了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

获取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的路径。

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

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);}
        }
}

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

当然,正确地捕获异常等。这只是快速而肮脏的尝试将您的代码塑造成有效的东西。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM