在 Java 中创建和访问文件时的默认路径不应该使用 jar 吗?



当我从IDE(Netbeans(创建或访问文件时遇到问题,新文件弹出在项目的文件夹中,但当我从Linux终端、Linux mint终端命令运行jar时,文件访问在我的/home/user文件夹中。

下面的代码显示了我的"/home/user"文件夹的路径。

showMessageDialog(null, new File("").getAbsolutePath());

如有任何帮助,我们将不胜感激。

我发现了如何获得jar的路径。也许这会帮助其他人。

下面是一个返回jar文件夹路径的方法。

/**
* Gets the path to the folder of the jar file
* @return Returns the path to the jar's folder
* @throws UnsupportedEncodingException 
*/
static String getJarPath() throws UnsupportedEncodingException {
// Get path to the jar
String path = Test.class.getProtectionDomain().getCodeSource().getLocation().getPath();
// Decode the path whitespaces
String decodedPath = URLDecoder.decode(path, "UTF-8");
// Remove the jar from the end of the path //
// Path variable that will be returned
String newPath = File.separator;
// Path split by file separator
String[] pathSplit = decodedPath.split(File.separator);
// Add each of the strings to the new path except the last one
for (int i = 0; i < pathSplit.length-1; i++) {
// Add a link of the path
newPath += pathSplit[i] + File.separator;
}
// Return the path to the folder with the jar
return newPath;
}

相关内容

最新更新