使用下面这个PathUtil的getProgramPath()就可以获得当前程序运行的目录。
import javanetURL;
import javanetURLDecoder;
class PathUtil {
/
Get the env of windir, such as "C:\WINDOWS"
@return the env of windir value
/
public static String getWindir() {
return Systemgetenv("windir");
}
/
Get file separator, such as "/" on unix
@return the separator of file
/
public static String getFileSeparator() {
return SystemgetProperty("fileseparator");
}
/
Get line separator, such as "\n" on unix
@return the separator of line
/
public static String getLineSeparator() {
return SystemgetProperty("lineseparator");
}
/
Get programPath
@return programPath
/
public static String getProgramPath() {
Class<PathUtil> cls = PathUtilclass;
ClassLoader loader = clsgetClassLoader();
//
// Get the full name of the class
//
String clsName = clsgetName() + "class";
//
// Get the package that include the class
//
Package pack = clsgetPackage();
String path = "";
//
// Transform package name to path
//
if (pack != null) {
String packName = packgetName();
//
// Get the class's file name
//
clsName = clsNamesubstring(packNamelength() + 1);
//
// If package is simple transform package name to path directly,
// else transform package name to path by package name's
// constituent
//
path = packName;
if (pathindexOf("") > 0) {
path = pathreplace("", "/");
}
path = path + "/";
}
URL url = loadergetResource(path + clsName);
//
// Get path information form the instance of URL
//
String retPath = urlgetPath();
//
// Delete protocol name "file:" form path information
//
try {
int pos = retPathindexOf("file:");
if (pos > -1) {
retPath = retPathsubstring(pos + 5);
}
//
// Delete the information of class file from the information of
// path
//
pos = retPathindexOf(path + clsName);
retPath = retPathsubstring(0, pos - 1);
//
// If the class file was packageed into JAR eg file, delete the
// file name of the corresponding JAR eg
//
if (retPathendsWith("!")) {
retPath = retPathsubstring(0, retPathlastIndexOf("/"));
}
retPath = URLDecoderdecode(retPath, "utf-8");
} catch (Exception e) {
retPath = null;
eprintStackTrace();
}
return retPath;
}
}
测试类:
public class Test{
public static void main(String args[]){
String s = PathUtilgetProgramPath();
Systemoutprintln(s);
}
}
命名空间:SystemWindowsForms
ApplicationStartupPath 属性(返回String)
获取启动了应用程序的可执行文件的路径,不包括可执行文件的名称。
ApplicationExecutablePath 属性(返回String)
获取启动了应用程序的可执行文件的路径,包括可执行文件的名称。
文件夹1里还有子文件夹:文件夹2现在你运行文件夹1里的程序,
取运行目录() 后发现,路径是:C:\Documents and Settings\Administrator\桌面\文件夹1
此时,你取当前目录,路径相同。
要是程序上有通用对话框(打开文件)组件,那么,在打开一个文件以后,再重复取以上两条命令,发现,运行目录不变,
当前目录变成了通用对话框所打开的文件目录。
以上就是关于Java获取程序运行的当前工作目录全部的内容,包括:Java获取程序运行的当前工作目录、在VB.NET中如何取得当前目录的路径、易语言怎么取当前用户目录等相关内容解答,如果想了解更多相关内容,可以关注我们,你们的支持是我们更新的动力!
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)