如何在Java中获取当前工作目录?
我想使用Java访问我当前的工作目录 我的代码:如何在Java中获取当前工作目录?,java,java-io,Java,Java Io,我想使用Java访问我当前的工作目录 我的代码: String currentPath = new java.io.File(".").getCanonicalPath(); System.out.println("Current dir:" + currentPath); String currentDir = System.getProperty("user.dir"); System.out.println("
String currentPath = new java.io.File(".").getCanonicalPath();
System.out.println("Current dir:" + currentPath);
String currentDir = System.getProperty("user.dir");
System.out.println("Current dir using System:" + currentDir);
输出:
Current dir: C:\WINDOWS\system32
Current dir using System: C:\WINDOWS\system32
我的输出不正确,因为C驱动器不是我的当前目录
如何获取当前目录?在不同的Java实现中,当前工作目录的定义不同。对于Java7之前的某些版本,没有一致的方法来获取工作目录。您可以通过使用
-D
启动Java文件并定义一个变量来保存信息来解决这个问题
差不多
java -D com.mycompany.workingDir="%0"
那不太对,但你明白了。然后System.getProperty(“com.mycompany.workingDir”)
..是什么让您认为c:\windows\system32不是您当前的目录?该属性显式为“用户的当前工作目录”
换句话说,除非您从命令行启动Java,否则c:\windows\system32可能是您的CWD。也就是说,如果您双击启动程序,那么CWD不太可能是您双击的源目录
编辑:这似乎仅适用于旧windows和/或Java版本 代码:
public class JavaApplication {
public static void main(String[] args) {
System.out.println("Working Directory = " + System.getProperty("user.dir"));
}
}
这将打印初始化应用程序的当前目录的绝对路径
说明:
public class JavaApplication {
public static void main(String[] args) {
System.out.println("Working Directory = " + System.getProperty("user.dir"));
}
}
从:
java.io
包使用当前用户目录解析相对路径名。当前目录表示为系统属性,即,user.dir
是调用JVM的目录。我希望您希望访问包括包在内的当前目录,也就是说,如果您的Java程序位于c:\myApp\com\foo\src\service\MyTest.Java
中,并且您希望打印到c:\myApp\com\foo\src\service
,那么您可以尝试以下代码:
String myCurrentDir = System.getProperty("user.dir")
+ File.separator
+ System.getProperty("sun.java.command")
.substring(0, System.getProperty("sun.java.command").lastIndexOf("."))
.replace(".", File.separator);
System.out.println(myCurrentDir);
注意:此代码仅在使用Oracle JRE的Windows中测试。请参阅:
使用java.nio.file.Path
和java.nio.file.Path
,您可以执行以下操作来显示java认为当前路径是什么。这适用于7和更高版本,并使用NIO
Path currentRelativePath = Paths.get("");
String s = currentRelativePath.toAbsolutePath().toString();
System.out.println("Current absolute path is: " + s);
这将产生:
Current relative path is: /Users/george/NetBeansProjects/Tutorials
就我而言,这就是我上课的地方
以相对方式构造路径,不使用前导分隔符表示正在构造绝对路径,将使用此相对路径作为起点。这是我的解决方案
this.getClass().getClassLoader().getResource("").getPath()
File currentDir = new File("");
这是当前目录名
String path="/home/prasad/Desktop/folderName";
File folder = new File(path);
String folderName=folder.getAbsoluteFile().getName();
这是当前目录路径
String path=folder.getPath();
我使用的是Linux,这两种方法得到的结果相同:
@Test
public void aaa()
{
System.err.println(Paths.get("").toAbsolutePath().toString());
System.err.println(System.getProperty("user.dir"));
}
使用
这在JAR文件中也可以很好地工作。您可以通过获得CodeSource
,而ProtectionDomain
又可以通过获得
以下内容适用于Java7及以上版本(有关文档,请参阅)
System.getProperty(“java.class.path”)
通常,作为文件对象:
File getCwd() {
return new File("").getAbsoluteFile();
}
您可能需要像“D:/a/b/c”这样的完全限定字符串来执行以下操作:
这里贴的答案对我都不管用。以下是我们所做的工作:
java.nio.file.Paths.get(
getClass().getProtectionDomain().getCodeSource().getLocation().toURI()
);
编辑:我的代码中的最终版本:
URL myURL = getClass().getProtectionDomain().getCodeSource().getLocation();
java.net.URI myURI = null;
try {
myURI = myURL.toURI();
} catch (URISyntaxException e1)
{}
return java.nio.file.Paths.get(myURI).toFile().toString()
假设您正试图在eclipse、netbean或独立于命令行运行项目。我已经写了一个方法来修复它
public static final String getBasePathForClass(Class<?> clazz) {
File file;
try {
String basePath = null;
file = new File(clazz.getProtectionDomain().getCodeSource().getLocation().toURI().getPath());
if (file.isFile() || file.getPath().endsWith(".jar") || file.getPath().endsWith(".zip")) {
basePath = file.getParent();
} else {
basePath = file.getPath();
}
// fix to run inside eclipse
if (basePath.endsWith(File.separator + "lib") || basePath.endsWith(File.separator + "bin")
|| basePath.endsWith("bin" + File.separator) || basePath.endsWith("lib" + File.separator)) {
basePath = basePath.substring(0, basePath.length() - 4);
}
// fix to run inside netbean
if (basePath.endsWith(File.separator + "build" + File.separator + "classes")) {
basePath = basePath.substring(0, basePath.length() - 14);
}
// end fix
if (!basePath.endsWith(File.separator)) {
basePath = basePath + File.separator;
}
return basePath;
} catch (URISyntaxException e) {
throw new RuntimeException("Cannot firgue out base path for class: " + clazz.getName());
}
}
公共静态最终字符串getBasePathForClass(类clazz){
文件;
试一试{
字符串basePath=null;
file=新文件(clazz.getProtectionDomain().getCodeSource().getLocation().toURI().getPath());
if(file.isFile()| | file.getPath().endsWith(“.jar”)| | file.getPath().endsWith(“.zip”)){
basePath=file.getParent();
}否则{
basePath=file.getPath();
}
//修复在eclipse中运行
if(basePath.endsWith(File.separator+“lib”)| | basePath.endsWith(File.separator+“bin”)
||basePath.endsWith(“bin”+File.separator)| | basePath.endsWith(“lib”+File.separator)){
basePath=basePath.substring(0,basePath.length()-4);
}
//修复在netbean中运行
if(basePath.endsWith(File.separator+“build”+File.separator+“classes”)){
basePath=basePath.substring(0,basePath.length()-14);
}
//端部固定
如果(!basePath.endsWith(File.separator)){
basePath=basePath+File.separator;
}
返回基本路径;
}捕获(URISyntaxException e){
抛出新的RuntimeException(“无法计算出类的基本路径:+clazz.getName());
}
}
若要使用,无论您想在何处获得读取文件的基本路径,都可以将锚点类传递给上述方法,结果可能是您需要的:D
最好的方法是,在Linux上运行jar文件时,无论jar文件在哪里,它们都将返回相同的
字符串:“/home/CurrentUser”。这取决于启动jar文件时终端使用的当前目录
Paths.get("").toAbsolutePath().toString();
System.getProperty("user.dir");
如果使用main
的Class
将被称为MainClass
,请尝试:
MainClass.class.getProtectionDomain().getCodeSource().getLocation().getFile();
这将返回一个字符串,其中包含jar文件的绝对路径。使用Windows user.dir按预期返回目录,但在您以提升权限(以管理员身份运行)启动应用程序时不会返回该目录,在这种情况下,您会得到C:\WINDOWS\system32请注意,它只在WINDOWS
中检查,但我认为它在其他操作系统[Linux、MacOs、Solaris
]上工作得非常完美:)。
我在同一个目录中有2个.jar
文件。我想从一个.jar
文件启动同一目录下的另一个.jar
文件
问题是,当您从cmd
启动它时,当前目录是system32
警告Paths.get("").toAbsolutePath().toString();
System.getProperty("user.dir");
MainClass.class.getProtectionDomain().getCodeSource().getLocation().getFile();
Path path = FileSystems.getDefault().getPath(".");
Path path = FileSystems.getDefault().getPath("Foo.txt");
Path path = FileSystems.getDefault().getPath(".").toAbsolutePath();
Path path = FileSystems.getDefault().getPath("").toAbsolutePath();
Path cwd = Path.of("").toAbsolutePath();
String cwd = Path.of("").toAbsolutePath().toString();
public static void callJVisualVM() {
System.out.println("USER:DIR!:" + System.getProperty("user.dir"));
//next search current jdk/jre
String jre_root = null;
String start = "vir";
try {
java.lang.management.RuntimeMXBean runtime =
java.lang.management.ManagementFactory.getRuntimeMXBean();
String jvmName = runtime.getName();
System.out.println("JVM Name = " + jvmName);
long pid = Long.valueOf(jvmName.split("@")[0]);
System.out.println("JVM PID = " + pid);
Runtime thisRun = Runtime.getRuntime();
jre_root = System.getProperty("java.home");
System.out.println("jre_root:" + jre_root);
start = jre_root.concat("\\..\\bin\\jvisualvm.exe " + "--openpid " + pid);
thisRun.exec(start);
} catch (Exception e) {
System.getProperties().list(System.out);
e.printStackTrace();
}
}
import java.io.File;
public class Find_this_dir {
public static void main(String[] args) {
//some sort of a bug in java path is correct but file dose not exist
File this_dir = new File("");
//but these both commands work too to get current dir
// File this_dir_2 = new File(this_dir.getAbsolutePath());
File this_dir_2 = new File(new File("").getAbsolutePath());
System.out.println("new File(" + "\"\"" + ")");
System.out.println(this_dir.getAbsolutePath());
System.out.println(this_dir.exists());
System.out.println("");
System.out.println("new File(" + "new File(" + "\"\"" + ").getAbsolutePath()" + ")");
System.out.println(this_dir_2.getAbsolutePath());
System.out.println(this_dir_2.exists());
}
}
var path = Path.of(".").toRealPath();
String currentDir = System.getenv("PWD");
/*
/home/$User/Documents/java
*/
//Home directory
String HomeDir = System.getEnv("HOME");
//Outputs for unix
/home/$USER
//Device user
String user = System.getEnv("USERNAME");
//Outputs for unix
$USER