在Java中获取当前工作目录

我想要使​​用我的当前工作目录

String current = new java.io.File( "." ).getCanonicalPath(); System.out.println("Current dir:"+current); 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盘不是我当前的目录。 在这方面需要帮助。

 public class JavaApplication1 { public static void main(String[] args) { System.out.println("Working Directory = " + System.getProperty("user.dir")); } } 

这将打印一个完整的绝对path,从你的应用程序初始化的地方。

请参阅: http : //docs.oracle.com/javase/tutorial/essential/io/pathOps.html

使用java.nio.file.Pathjava.nio.file.Paths ,可以执行以下操作来显示Java认为是当前path的内容。 这对于7,并使用NIO。

 Path currentRelativePath = Paths.get(""); String s = currentRelativePath.toAbsolutePath().toString(); System.out.println("Current relative path is: " + s); 

这个输出Current relative path is: /Users/george/NetBeansProjects/Tutorials ,在我的情况下是我从哪里跑的类。 以相对的方式构buildpath,通过不使用前导分隔符来指示您正在构build绝对path,将使用此相对path作为起点。

下面的工作在Java 7及以上(请参阅这里的文档)。

 import java.nio.file.Paths; Paths.get(".").toAbsolutePath().normalize().toString(); 

是什么让你认为c:\ windows \ system32不是你当前的目录? user.dir属性显式为“用户当前工作目录”。

换句话说,除非你从命令行启动Java,否则c:\ windows \ system32可能就是你的CWD。 也就是说,如果你双击启动你的程序,CWD不太可能是你双击的目录。

编辑 :这似乎只适用于旧的Windows和/或Java版本。

这是我的解决scheme

 File currentDir = new File(""); 
 this.getClass().getClassLoader().getResource("").getPath() 

使用CodeSource#getLocation()

这在JAR文件中也可以正常工作。 您可以通过ProtectionDomain#getCodeSource()获取CodeSource ,而ProtectionDomain又可以通过Class#getProtectionDomain()

 public class Test { public static void main(String... args) throws Exception { URL location = Test.class.getProtectionDomain().getCodeSource().getLocation(); System.out.println(location.getFile()); } } 

一般来说,作为一个File对象:

 File getCwd() { return new File("").getAbsoluteFile(); } 

你可能想要像“D:/ a / b / c”这样的全限定string:

 getCwd().getAbsolutePath() 

我在Linux上,并获得相同的结果,这两种方法:

 @Test public void aaa() { System.err.println(Paths.get("").toAbsolutePath().toString()); System.err.println(System.getProperty("user.dir")); } 

Paths.get("")文档

System.getProperty("user.dir")文档

我希望你想访问当前目录,包括包如果你的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中进行testing。

使用Windows用户.dir返回目录按预期方式,但不是当您提升权限(以pipe理员身份运行)启动您的应用程序,在这种情况下,您得到C:\ WINDOWS \ system32

当前的工作目录在不同的Java实现中有不同的定义。 对于Java 7之前的某些版本,没有一致的方法来获取工作目录。 您可以通过启动带有-D Java文件并定义一个variables来保存信息来解决此问题

就像是

 java -D com.mycompany.workingDir="%0" 

这不太对,但你明白了。 然后System.getProperty("com.mycompany.workingDir")

Linux上,当你从terminal运行一个jar文件时,这两者都会返回相同的String“/ home / CurrentUser” ,无论你在哪里jar文件是。 这取决于您在启动jar文件时使用的terminal的当前目录。

 Paths.get("").toAbsolutePath().toString(); System.getProperty("user.dir"); 

如果你的Classmain被称为MainClass ,然后尝试:

 MainClass.class.getProtectionDomain().getCodeSource().getLocation().getFile(); 

这将返回一个Stringjar文件的绝对path

提到它只在Windows检查,但我认为它适用于其他操作系统[ Linux,MacOs,Solaris ] :)。


我在同一个目录中有两个 .jar文件。 我想从一个.jar文件中启动另一个.jar文件,它位于同一目录中。

问题是,当你从cmd启动它时,当前目录是system32


警告!

  • 下面似乎工作得很好,我已经完成了所有的testing文件夹名称;][[;'57f2g34g87-8+9-09!2#@!$%^^&() ()%&$%^@#它运作良好。
  • 我正在使用下面的ProcessBuilder ,如下所示:

🍂..

 //The class from which i called this was the class `Main` String path = getBasePathForClass(Main.class); String applicationPath= new File(path + "application.jar").getAbsolutePath(); System.out.println("Directory Path is : "+applicationPath); //Your know try catch here //Mention that sometimes it doesn't work for example with folder `;][[;'57f2g34g87-8+9-09!2#@!$%^^&()` ProcessBuilder builder = new ProcessBuilder("java", "-jar", applicationPath); builder.redirectErrorStream(true); Process process = builder.start(); //...code 

🍂getBasePathForClass getBasePathForClass(Class<?> classs)

  /** * Returns the absolute path of the current directory in which the given * class * file is. * * @param classs * @return The absolute path of the current directory in which the class * file is. * @author GOXR3PLUS[StackOverFlow user] + bachden [StackOverFlow user] */ public static final String getBasePathForClass(Class<?> classs) { // Local variables File file; String basePath = ""; boolean failed = false; // Let's give a first try try { file = new File(classs.getProtectionDomain().getCodeSource().getLocation().toURI().getPath()); if (file.isFile() || file.getPath().endsWith(".jar") || file.getPath().endsWith(".zip")) { basePath = file.getParent(); } else { basePath = file.getPath(); } } catch (URISyntaxException ex) { failed = true; Logger.getLogger(classs.getName()).log(Level.WARNING, "Cannot firgue out base path for class with way (1): ", ex); } // The above failed? if (failed) { try { file = new File(classs.getClassLoader().getResource("").toURI().getPath()); basePath = file.getAbsolutePath(); // the below is for testing purposes... // starts with File.separator? // String l = local.replaceFirst("[" + File.separator + // "/\\\\]", "") } catch (URISyntaxException ex) { Logger.getLogger(classs.getName()).log(Level.WARNING, "Cannot firgue out base path for class with way (2): ", ex); } } // 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 netbeans 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; } 

这里没有任何答案为我工作。 这是什么工作:

 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()); } } 

要使用的地方,你想获得基本path读取文件的任何地方,你可以传递你的锚类到上面的方法,结果可能是你需要的东西:D

最好,

这会给你工作目录的path:

 Path path = FileSystems.getDefault().getPath("."); 

这会给你一个在工作目录下名为“Foo.txt”的文件的path:

 Path path = FileSystems.getDefault().getPath("Foo.txt"); 

这是当前的目录名称

 String path="/home/prasad/Desktop/folderName"; File folder = new File(path); String folderName=folder.getAbsoluteFile().getName(); 

这是当前的目录path

 String path=folder.getPath(); 

System.getProperty("java.class.path")