[英]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.