Java print working directory

How to get a current working directory in Java

Many candidates are rejected or down-leveled due to poor performance in their System Design Interview. Stand out in System Design Interviews and get hired in 2023 with this popular free course.

Problem overview

In this shot, we will discuss how to write a Java program to print the current working directory in which a program is executed.

Solution

We use the Path class from the java.nio.file package and then perform the following steps.

  1. Pass an empty string to the Paths.get() method to get the current relative path.
  2. Use the toAbsolutePath() method to convert the relative path to absolute path.
  3. Call the toString() method on the absolute path to convert the absolute path to string.

Code

import java.nio.file.Path;
import java.nio.file.Paths;
public class Main
public static void main(String[] args)
Path currRelativePath = Paths.get("");
String currAbsolutePathString = currRelativePath.toAbsolutePath().toString();
System.out.println("Current absolute path is - " + currAbsolutePathString);
>
>

Learn in-demand tech skills in half the time

Источник

Get the Current Working Directory in Java

announcement - icon

The Kubernetes ecosystem is huge and quite complex, so it’s easy to forget about costs when trying out all of the exciting tools.

To avoid overspending on your Kubernetes cluster, definitely have a look at the free K8s cost monitoring tool from the automation platform CAST AI. You can view your costs in real time, allocate them, calculate burn rates for projects, spot anomalies or spikes, and get insightful reports you can share with your team.

Connect your cluster and start monitoring your K8s costs right away:

We rely on other people’s code in our own work. Every day.

It might be the language you’re writing in, the framework you’re building on, or some esoteric piece of software that does one thing so well you never found the need to implement it yourself.

The problem is, of course, when things fall apart in production — debugging the implementation of a 3rd party library you have no intimate knowledge of is, to say the least, tricky.

Lightrun is a new kind of debugger.

It’s one geared specifically towards real-life production environments. Using Lightrun, you can drill down into running applications, including 3rd party dependencies, with real-time logs, snapshots, and metrics.

Learn more in this quick, 5-minute Lightrun tutorial:

announcement - icon

Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.

The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.

Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.

Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:

announcement - icon

DbSchema is a super-flexible database designer, which can take you from designing the DB with your team all the way to safely deploying the schema.

The way it does all of that is by using a design model, a database-independent image of the schema, which can be shared in a team using GIT and compared or deployed on to any database.

And, of course, it can be heavily visual, allowing you to interact with the database using diagrams, visually compose queries, explore the data, generate random data, import data or build HTML5 database reports.

announcement - icon

The Kubernetes ecosystem is huge and quite complex, so it’s easy to forget about costs when trying out all of the exciting tools.

To avoid overspending on your Kubernetes cluster, definitely have a look at the free K8s cost monitoring tool from the automation platform CAST AI. You can view your costs in real time, allocate them, calculate burn rates for projects, spot anomalies or spikes, and get insightful reports you can share with your team.

Connect your cluster and start monitoring your K8s costs right away:

We’re looking for a new Java technical editor to help review new articles for the site.

1. Overview

It’s an easy task to get the current working directory in Java, but unfortunately, there’s no direct API available in the JDK to do this.

In this tutorial, we’ll learn how to get the current working directory in Java with java.lang.System, java.io.File, java.nio.file.FileSystems, and java.nio.file.Paths.

2. System

Let’s begin with the standard solution using System#getProperty, assuming our current working directory name is Baeldung throughout the code:

static final String CURRENT_DIR = "Baeldung"; @Test void whenUsingSystemProperties_thenReturnCurrentDirectory()

We used a Java built-in property key user.dir to fetch the current working directory from the System‘s property map. This solution works across all JDK versions.

3. File

Let’s see another solution using java.io.File:

@Test void whenUsingJavaIoFile_thenReturnCurrentDirectory()

Here, the File#getAbsolutePath internally uses System#getProperty to get the directory name, similar to our first solution. It’s a nonstandard solution to get the current working directory, and it works across all JDK versions.

4. FileSystems

Another valid alternative would be to use the new java.nio.file.FileSystems API:

@Test void whenUsingJavaNioFileSystems_thenReturnCurrentDirectory()

This solution uses the new Java NIO API, and it works only with JDK 7 or higher.

5. Paths

And finally, let’s see a simpler solution to get the current directory using java.nio.file.Paths API:

@Test void whenUsingJavaNioPaths_thenReturnCurrentDirectory()

Here, Paths#get internally uses FileSystem#getPath to fetch the path. It uses the new Java NIO API, so this solution works only with JDK 7 or higher.

6. Conclusion

In this tutorial, we explored four different ways to get the current working directory in Java. The first two solutions work across all versions of the JDK whereas the last two work only with JDK 7 or higher.

We recommend using the System solution since it’s efficient and straight forward, we can simplify it by wrapping this API call in a static utility method and access it directly.

The source code for this tutorial is available over on GitHub – it is a Maven-based project, so it should be easy to import and run as-is.

announcement - icon

Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.

The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.

Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.

Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:

Источник

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

Источник

Java – How to get Current Directory in Linux/Windows

Java Tutorial for Beginners

Java – How do I get the directory that a program is running from?

In this Tutorial We will learn how to print the path of current working directory. The code below is applicable for both Linux and window.

/*********************************************************************** * * * This will print a complete absolute path from where your application was initialized * * ********************************************************************** **/ public class app < public static void main(String[] args) < System.out.println("Working Directory = " + System.getProperty("user.dir")); >> /* OUTPUT Working Directory = C:\Users\codebind\Projects\App */

Other way of Getting the Current Working Directory in Java is by using java.io.File

/*********************************************************************** * * * This will print a complete absolute path from where your application was initialized * * ********************************************************************** **/ import java.io.File; public class app < public static void main(String[] args) < File currentDir = new File(""); System.out.println("Working Directory : " + currentDir.getAbsoluteFile()); >> /* OUTPUT Working Directory = C:\Users\codebind\Projects\App */

Источник

Читайте также:  Задача коммивояжера муравьиный алгоритм java
Оцените статью