简体   繁体   English

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

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

I have already surveyed SO for an answer, and could not find an appropriate one. 我已经调查了SO的答案,但找不到合适的答案。

When I launch my program from a jar I need to create a folder in the directory where the jar file is located. 当我从jar启动程序时,我需要在jar文件所在的目录中创建一个文件夹。 It should not matter where the user saves the jar file. 用户保存jar文件的位置无关紧要。

Here is the newest code I was playing with: A System.out.println will print out the correct directory but the folder will not be created. 这是我正在使用的最新代码: System.out.println将打印出正确的目录,但不会创建该文件夹。 In contrast,everything is being saved to my System32 folder as of now. 相比之下,到目前为止,所有内容都保存到我的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

To get a Jar's path can be a little trickier than simply getting the user.dir directory. 获取Jar的路径可能比简单地获取user.dir目录有点棘手。 I can't remember the details why, but user.dir does not return this path reliably in all situations. 我不记得详细原因,但user.dir在所有情况下都不能可靠地返回此路径。 If you absolutely must get the jar's path, then you need to do a little black magic and first get the class's protectionDomain. 如果你绝对必须得到jar的路径,那么你需要做一点黑魔法并首先得到类的保护域。 Something like: 就像是:

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

Even this isn't guaranteed to work, and you'll have to resign yourself to the fact that there are just some times (for instance for security reasons) when you won't be able to get a Jar's path. 即使这不能保证工作,你也必须让自己辞职,因为有些时候(例如出于安全原因)你将无法获得Jar的路径。

With some changes (such as adding a "/" before Comics), I managed to create the directory where you expected it to. 通过一些更改(例如在漫画之前添加“/”),我设法创建了您期望的目录。 Here is the full code I used. 这是我使用的完整代码。

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

In the future, please don't hard code things like "/" and such. 将来,请不要硬编码“/”之类的东西。 Use built-in libraries which will ask the OS what is right in this case. 使用内置库,这将询问操作系统在这种情况下的正确性。 This ensures the functionality doesn't break (as easily) cross platform. 这确保了功能不会(很容易)跨平台。

Of course, catch the exception properly etc. This is just quick and dirty attempt to mold your code into something that works. 当然,正确地捕获异常等。这只是快速而肮脏的尝试将您的代码塑造成有效的东西。

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

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