Mic*_*ott 5 java directory path
我已经调查过 SO 以获得答案,但找不到合适的答案。
当我从 jar 启动我的程序时,我需要在 jar 文件所在的目录中创建一个文件夹。用户将 jar 文件保存在哪里应该无关紧要。
这是我正在使用的最新代码: ASystem.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
Run Code Online (Sandbox Code Playgroud)
获取 Jar 的路径可能比简单获取 user.dir 目录要复杂一些。我不记得具体原因,但 user.dir 并不能在所有情况下可靠地返回此路径。如果您绝对必须获取 jar 的路径,那么您需要执行一些黑魔法并首先获取类的 protectedDomain。就像是:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
即使这也不能保证有效,并且您必须接受这样一个事实:只有某些时候(例如出于安全原因)您将无法获得 Jar 的路径。