Java current dir path

Determine current working directory in Java

In this article, we are going to present how to get the current working directory in Java.

Follow this link to check more Java IO related articles

2. Using system property user.dir

According to JDK 7 documentation current user directory is named by the system property user.dir , and is typically the directory in which the JVM was invoked.

Let’s create a simple POC (proof of concept) application to check how this property behaves when we run the program from different folders.

Читайте также:  Javascript events option in select

This sample Maven application will be using maven-jar-plugin to build the executable jar file.

The pom.xml file has the following structure:

  4.0.0 java-io-working-directory jar com.frontbackend.java 1.0-SNAPSHOT   org.apache.maven.plugins maven-jar-plugin   true libs/ com.frontbackend.java.io.working.dir.WorkingDirectory        

The WorkingDirectory is our base class that contains main(. ) method, that starts the program:

package com.frontbackend.java.io.working.dir; public class WorkingDirectory < public static void main(String[] args) < String userDirectory = System.getProperty("user.dir"); System.out.println("Working dir = " + userDirectory); >> 

In pom.xml we need to point this class in configuration.archive.manifest.mainClass path:

 com.frontbackend.java.io.working.dir.WorkingDirectory 

Now let’s build our application using mvn install command:

We run this commend in /home/frontbackend/tutorials/java/java-io-working-directory folder:

$ mvn clean install $ cd target $ java -jar java-io-working-directory-1.0-SNAPSHOT.jar 
Working dir = /home/frontbackend/tutorials/java/java-io-working-directory/target 

After we copy application JAR file to /tmp folder:

$ cp java-io-working-directory-1.0-SNAPSHOT.jar /tmp $ cd /tmp $ java -jar java-io-working-directory-1.0-SNAPSHOT.jar 

3. Get a working directory in Windows

Things are slightly different in the Windows operation system. Printing user.dir system parameter in Windows could give you results as: C:\WINDOWS\system32 , because in most cases user-working-directory will be pointing to current-working-directory of a system process (cwd).

When you need to determine the current working directory in Java application running on Windows, you could check the following example snippets (probably one should work just fine for you):

Using FileSystems.getDefault() method:

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

Using getClass().getProtectionDomain().getCodeSource() method:

URL location = WorkingDirectory.class.getProtectionDomain().getCodeSource().getLocation(); System.out.println(location.getFile()); 
Path path = FileSystems.getDefault().getPath("."); 

4. Conclusion

In this article, we presented how to get the current working directory in Java applications. Unfortunately dedicated system property ( user.dir ) that should hold a current working directory works a little bit different in Windows and Linux operating systems. That because in Windows Java applications are handled by the system and running as a process using C:\WINDOWS\system32 libraries. Depending on how you start your Java program in Windows you will need to use a different approach. You can start by checking our example snippets available also on GitHub.

Источник

Get current directory path in java

Getting the path of current directory is often required when you need to access some files from code generally for reading text or properties files.

This article will explain 4 different ways to get the path of current working directory in java or from java code.

Method 1 : Using System property
Java has defined some properties which are used to get information about its environment. One of such property is user.dir which gives the path of current working directory.

In order to retrieve the value of java properties, getProperty() method of java.lang.System class is used. This method is static and takes a string argument, which is the name of property.
Example,

String currentPath = System.getProperty("user.dir"); System.out.println("Current path is:: " + currentPath);

If you run this code from an IDE such as eclipse, then it will return the absolute path of the current project.

Method 2 : Using File class
java.io.File class has a constructor which takes a string argument. This argument represents the path to which the file object points.

Providing an empty path means that the file object is pointed to the current folder. Invoke getAbsolutePath() on the file object to get the complete path of current directory as shown below.

// create file object for current folder File file = new File(""); String currentPath = file.getAbsolutePath(); System.out.println("Current path is:: " + currentPath);

Method 3 : Using Paths
java.nio.file.Paths class introduced in java 7 is a utility class that contains static methods related to paths. It has a static get() method which takes a string argument representing a file path and returns an object of java.nio.file.Path .

Supplying empty string to get() means the current working directory.
Path object points to a physical file and its toAbsolutePath() method returns another Path object containing the absolute path of the file.

Invoke toString() method on this Path object to get the path of current working directory.
Java program code for this method is given below.

Path currentDirectoryPath = Paths.get("").toAbsolutePath(); String currentPath = currentDirectoryPath.toString(); System.out.println("Current directory path:: " + currentPath);

Method 4 : Using FileSystems class
For dealing with file system, java provides a class java.nio.file.FileSystem . Object of FileSystem can be retrieved using java.nio.file.FileSystems class using its static getDefault() method.

FileSystem has a getPath() method which takes a string argument representing the path of a file.
Supplying it an empty string means the current directory.
getPath() returns an object of Path and you can use its toAbsolutePath() method to get the full path of current directory.
Example,

FileSystem fileSystem = FileSystems.getDefault(); Path path = fileSystem.getPath("").toAbsolutePath() String currentDirectoryPath = path.toString();

Above code can be written as one-liner

String currentDirectoryPath = FileSystems.getDefault(). getPath(""). toAbsolutePath(). toString();

Hope the article was useful, click the clap below if you liked it.

Share your thoughts !! Cancel reply

Java Concepts

  • Instance variables
  • Create object in 5 ways
  • Constructors with example
  • Constructor chaining
  • Access specifiers/modifiers
  • public static void main
  • Reading user input in java
  • Abstract class
  • Abstract method
  • Interfaces
  • Method Overloading
  • Method Overriding
  • this keyword
  • static keyword
  • Arrays
  • 2d arrays
  • switch-case statement
  • Ternary operator
  • Enhanced for loop
  • continue statement
  • break statement
  • Exception handling
  • throw and throws
  • Java try-with-resources
  • NullPointerException
  • IllegalStateException java
  • Inner classes
  • Marker interface
  • Serialization and deserialization in java
  • Convert nanoseconds to seconds
  • Get current directory path in 4 ways
  • Comparator interface
  • GET/POST request with HttpClient
  • Set default java version on Mac OS
  • Install openjdk on Mac OS from tar file
  • Math.random()
  • BufferedReader class to read text file and user input
  • Immutable class in java
  • boolean in java
  • Java StringBuffer class
  • Java scanner class
  • AutoCloseable interface in java

Источник

How to get current working directory in java

You can use Paths.get(«») method get current working directory in java.

When I ran above program, I got below output:

Using FileSystems.getDefault() (Java 7+)

You can use FileSystem.getDefault() method get current working directory in java.

When I ran above program, I got below output:

That’s all about how to get current working directory in java.

Was this post helpful?

Count Files in Directory in Java

Count Files in Directory in Java

How to Remove Extension from Filename in Java

How to Remove Extension from Filename in Java

How to Get Temp Directory Path in Java

How to Get Temp Directory Path in Java

Convert OutputStream to byte array in java

Convert Outputstream to Byte Array in Java

How to get current working directory in java

How to get current working directory in java

Difference between Scanner and BufferReader in java

Difference between Scanner and BufferReader in java

Read UTF-8 Encoded Data in java

Read UTF-8 Encoded Data in java

WriteUTF-8NewBufferWriter

Write UTF-8 Encoded Data in java

Java read file line by line

Java read file line by line

Java FileWriter Example

Java FileWriter Example

Java FileReader Example

Java FileReader Example

Java - Create new file

Java – Create new file

Share this

Author

Count Files in Directory in Java

Count Files in Directory in Java

Table of ContentsUsing java.io.File ClassUse File.listFiles() MethodCount Files in the Current Directory (Excluding Sub-directories)Count Files in the Current Directory (Including Sub-directories)Count Files & Folders in Current Directory (Excluding Sub-directories)Count Files & Folders in Current Directory (Including Sub-directories)Use File.list() MethodUsing java.nio.file.DirectoryStream ClassCount Files in the Current Directory (Excluding Sub-directories)Count Files in the Current Directory (Including Sub-directories)Count […]

How to Remove Extension from Filename in Java

Table of ContentsWays to Remove extension from filename in javaUsing substring() and lastIndexOf() methodsUsing replaceAll() methodUsing Apache common library In this post, we will see how to remove extension from filename in java. Ways to Remove extension from filename in java There are multiple ways to remove extension from filename in java. Let’s go through […]

How to Get Temp Directory Path in Java

Table of ContentsGet Temp Directory Path in JavaUsing System.getProperty()By Creating Temp File and Extracting Temp PathUsing java.io.FileUsing java.nio.File.FilesOverride Default Temp Directory Path In this post, we will see how to get temp directory path in java. Get Temp Directory Path in Java Using System.getProperty() To get the temp directory path, you can simply use System.getProperty(«java.io.tmpdir»). […]

Convert OutputStream to byte array in java

Convert Outputstream to Byte Array in Java

Table of ContentsConvert OutputStream to Byte array in JavaConvert OutputStream to ByteBuffer in Java In this post, we will see how to convert OutputStream to Byte array in Java. Convert OutputStream to Byte array in Java Here are steps to convert OutputStream to Byte array in java. Create instance of ByteArrayOutputStream baos Write data to […]

Difference between Scanner and BufferReader in java

Table of ContentsIntroductionScannerBufferedReaderDifference between Scanner and BufferedReader In this post, we will see difference between Scanner and BufferReader in java. Java has two classes that have been used for reading files for a very long time. These two classes are Scanner and BufferedReader. In this post, we are going to find major differences and similarities […]

Read UTF-8 Encoded Data in java

Table of ContentsUsing Files’s newBufferedReader()Using BufferedReaderUsing DataInputStream’s readUTF() method In this post, we will see how to read UTF-8 Encoded Data. Sometimes, we have to deal with UTF-8 Encoded Data in our application. It may be due localization or may be processing data from user input. There are multiple ways to read UTF-8 Encoded Data […]

Источник

Оцените статью