How to get the current working directory in Java?

前端 未结 22 3114
时光说笑
时光说笑 2020-11-21 07:16

I want to access my current working directory using java.

My code :

 String current = new java.io.File( \".\" ).getCanonicalPath();
        System.ou         


        
相关标签:
22条回答
  • 2020-11-21 08:00

    None of the answers posted here worked for me. Here is what did work:

    java.nio.file.Paths.get(
      getClass().getProtectionDomain().getCodeSource().getLocation().toURI()
    );
    

    Edit: The final version in my code:

    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()
    
    0 讨论(0)
  • 2020-11-21 08:00

    this is current directory name

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

    this is current directory path

    String path=folder.getPath();
    
    0 讨论(0)
  • 2020-11-21 08:01

    See: http://docs.oracle.com/javase/tutorial/essential/io/pathOps.html

    Using java.nio.file.Path and java.nio.file.Paths, you can do the following to show what Java thinks is your current path. This for 7 and on, and uses NIO.

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

    This outputs Current relative path is: /Users/george/NetBeansProjects/Tutorials that in my case is where I ran the class from. Constructing paths in a relative way, by not using a leading separator to indicate you are constructing an absolute path, will use this relative path as the starting point.

    0 讨论(0)
  • 2020-11-21 08:01

    This is the solution for me

    File currentDir = new File("");
    
    0 讨论(0)
  • 2020-11-21 08:07
    this.getClass().getClassLoader().getResource("").getPath()
    
    0 讨论(0)
  • 2020-11-21 08:09

    The following works on Java 7 and up (see here for documentation).

    import java.nio.file.Paths;
    
    Paths.get(".").toAbsolutePath().normalize().toString();
    
    0 讨论(0)
提交回复
热议问题