Get current directory kotlin

Kotlin Path Interface

The Path interface is provided to Kotlin by the java.nio.file.Paths package. It represents Paths on the underlying file system and provides a number of useful utility methods for working with paths. Here is an example program followed by output and an explanation.

import java.io.BufferedWriter import java.io.FileWriter import java.nio.file.Paths val belchers = "belchers.txt" fun makeBelcherFile() < val names = listOf("Bob", "Linda", "Tina", "Gene", "Louise") BufferedWriter(FileWriter(belchers)).use < writer ->names.forEach < name ->with(writer) < write(name) newLine() >> > > fun main(args : Array) < //Just make a file on the file system for demonstration purposes makeBelcherFile() //Get a reference to our example path on the disk. //In this case, we are using Paths.get() to get a reference to the current working directory //and then using the resolve() method to add the belchers.txt file to the path val belcherPath = Paths.get(System.getProperty("user.dir")).resolve(belchers) val template = "\t%-30s =>%s" with(belcherPath)< println("File Information") //The fileName property returns the name of the file println(template.format("File Name", fileName)) //The root property return the the root folder of the path println(template.format("File Path Root", root)) //The parent property returns the parent folder of the file println(template.format("File Path Parent", parent)) //The nameCount returns how many items are in the path println(template.format("Name Count", nameCount)) //The subpath() method returns a portion of the path println(template.format("Subpath (0, 1)", subpath(0, 1))) //The normalize method returns items such as . or .. from the path println(template.format("Normalizing", normalize())) //True if this is an absolute path otherwise false println(template.format("Is Absolute Path?", isAbsolute)) //Convert to an absolute path if needed println(template.format("Absolute Path", toAbsolutePath())) //Check if the path starts with a path. In this example, we are using the home folder println(template.format("Starts with $?", startsWith(System.getProperty("user.home")))) println() println("Elements of the Path") //We can print each portion of the path individually also! forEach < it ->println("\tPortion => $it") > > >

Here is the output when run on my machine.

File Information File Name => belchers.txt File Path Root => / File Path Parent => /Users/stonesoup/IdeaProjects/OCJAP Name Count => 5 Subpath (0, 1) => Users Normalizing => /Users/stonesoup/IdeaProjects/OCJAP/belchers.txt Is Absolute Path? => true Absolute Path => /Users/stonesoup/IdeaProjects/OCJAP/belchers.txt Starts with /Users/stonesoup? => true Elements of the Path Portion => Users Portion => stonesoup Portion => IdeaProjects Portion => OCJAP Portion => belchers.txt

Explanation

The program writes out a basic text file to the file system for demonstration purposes. We are going to focus on the main function. Our first task is to get a Path object that points to our belchers.txt file. We use the Paths.get() factory method and path in a path on the file system. In our example, we use the current working directory by using the System property “user.dir”.

We could have also added the belchers.txt to the end of the current working directory. However, I wanted to demonstrate the resolve method that combines two paths into a single path. So we chain the resolve method to the returned Path object and add belchers.txt. The returned Path object points to the path of belchers.txt on the file system.

Читайте также:  tag */ echo "$title

The next part of the program demonstrates commonly used methods found on the Path interface. Line 33 prints the name of the file by using the fileName property. Next we print out the root of the path by using the root property (line 36). When we want to know the parent of a path, we can use the parent property (line 39).

The Path interface has a nameCount property (line 42) that returns the number of items in a path. So if a path is /Users/stonesoup/IdeaProjects/OCJAP/belchers.txt , nameCount returns 5, one for each item between each slash (/) character. The nameCount is useful when working with the Subpath function (line 45), which accepts a start index (inclusive) and an end index (exclusive) and returns a Path object based on the indexes.

Sometimes paths are abnormal paths and may have “.” or “..” characters in the path. When we want to remove such characters, we use the normalize() function (line 48) which strips out abnormal characters from the path. Depending on the work we may be doing, we may want to test if the Path is a relative path or an abosulte path. The Path interface has an isAbsolute property (line 51) for such purposes. It returns true if the path is an absolute path otherwise false.

Should we wish to convert a relative path into an absolute path, we only need to call the toAbsolutePath() function (line 54) and we will get an absolute path. We can also check if a path starts with a certain path. In our example, line 57, we check if our path starts with the users home directory (user.home). It returns true or false based on the outcome.

Path supports the forEach() function. Line 62 shows an example of how we can iterate through each part of the Path. The it variable holds each portion of the path and the program prints each part of the path.

Common Methods

We spoke about each method as it relates the program above. Here are each of the commonly used methods broken down.

Paths.get(first : String, varages more : String) : Path

The get() converts a String (or URI in the overloaded version) into a Path object. When we use use the varags part, the Path will use the OS name seperator. So Unix paths will have a forward slash, while Windows ones will have a backslash.

val home = Paths.get(System.getProperty("user.home"))

parent : Path

The parent property returns a Path object that points to the parent of the current Path object.

nameCount : Int

The nameCount returns the number of items in the path.

subPath(beginIndex : Int, endIndex : Int) : Path

The subPath method is used to return a portion of the path object. The beginIndex is inclusive while the endIndex is exclusive.

normalize() : Path

The normalize() method returns a Path object without unneeded characters.

resolve(other : Path) : Path, resolve(other : String): Path

Returns a Path object that is a combined path between the current path and the other parameter.

val belchers = home.resolve("belchers.txt")

isAbsolute : Boolean

True if the Path is an absolute path otherwise it’s false.

val absolute = home.isAbsolute

startsWith(path : String) : Boolean, startsWith(path : Path) : Boolean

True if the current path starts with the supplied path argument.

val hasRoot = home.startsWith("/")

toAbsolutePath() : Path

Returns a Path object that is the aboslute path of the current Path.

val abs = home.toAbsolutePath()

Источник

How to get the current working directory in kotlin?

When working with a Kotlin program, it is sometimes necessary to obtain the current working directory, which is the directory in which the program is located. This information can be useful in a variety of scenarios, such as when reading or writing files relative to the program’s location. In this tutorial, we will go over different ways to get the current working directory in Kotlin.

Читайте также:  Phpmyadmin failed opening required streams php

Method 1: Using System Property «user.dir»

To get the current working directory in Kotlin using the System Property «user.dir» , you can use the following code:

val currentDir = System.getProperty("user.dir") println("Current working directory is: $currentDir")
  • System is a class in Java that provides access to system-specific properties and functions.
  • getProperty() is a method of the System class that returns the value of the specified system property.
  • «user.dir» is a system property that represents the current working directory of the user.
  • The above code gets the value of the «user.dir» system property and stores it in the currentDir variable.
  • The println() function is used to print the current working directory to the console.
Current working directory is: /path/to/current/directory

Note: The value of the «user.dir» system property may vary depending on the operating system and the way the program is executed.

Method 2: Using Kotlin File class

To get the current working directory in Kotlin using the File class, you can follow these steps:

  1. Create a new File object without any arguments. This will represent the current working directory.
  1. Get the absolute path of the File object using the absolutePath property. This will give you the current working directory as a string.
val currentDirPath = currentDir.absolutePath
  1. Alternatively, you can also use the canonicalPath property to get the canonical path of the File object, which will also give you the current working directory as a string.
val currentDirPath = currentDir.canonicalPath
import java.io.File fun main()  val currentDir = File("") val currentDirPath = currentDir.absolutePath println("Current working directory: $currentDirPath") >
Current working directory: /path/to/current/working/directory

Method 3: Using java.nio.file.Paths

To get the current working directory in Kotlin using java.nio.file.Paths , you can follow these steps:

  1. Call the Paths.get() method with no arguments to get a Path object representing the current working directory:
val currentDirStr = currentDir.toAbsolutePath().toString()

Here’s the complete example code:

import java.nio.file.Paths fun main()  val currentDir = Paths.get("") val currentDirStr = currentDir.toAbsolutePath().toString() println("Current working directory: $currentDirStr") >

This code will output the current working directory as a string.

Источник

How to get Current Working Directory in Kotlin

Kotlin is a powerful, statically-typed programming language developed by JetBrains. It is a Java-compatible language that can be used to create powerful, robust applications. In this article, we will look at how to get the current working directory in Kotlin.

The current working directory is the directory in which your program is currently running. It is the directory in which you can find the files and folders that are related to your program. Knowing the current working directory is important when you want to access files and folders in your program.

There are several ways to get the current working directory in Kotlin. The easiest way is to use the System.getProperty() method. This method takes a single argument, which is the name of the property you are looking for. In this case, we want to get the current working directory, so we will pass the “user.dir” parameter to the method. This will return the current working directory as a String:

val currentWorkingDirectory = System.getProperty("user.dir") println("Current working directory: $currentWorkingDirectory") 

The output of this code will be something like this:

Current working directory: /home/username

Another way to get the current working directory is to use the File class. This class provides several methods for working with files and directories. To get the current working directory, we can use the getAbsolutePath() method:

val currentWorkingDirectory = File("").absolutePath println("Current working directory: $currentWorkingDirectory") 

This code will also return the current working directory as a string.

We can also get the current working directory using the Environment class. This class provides several methods for accessing system environment variables. To get the current working directory, we can use the getProperty() method:

val currentWorkingDirectory = Environment.getProperty("user.dir") println("Current working directory: $currentWorkingDirectory") 

This code will also return the current working directory as a string.

Finally, we can use the System class to get the current working directory. The System class provides several methods for accessing system properties. To get the current working directory, we can use the getProperty() method:

val currentWorkingDirectory = System.getProperty("user.dir") println("Current working directory: $currentWorkingDirectory") 

This code will also return the current working directory as a string.

These are just a few of the ways to get the current working directory in Kotlin. There are other methods available, depending on your needs. If you need more control over the process, you can use the File class to get a File object representing the current working directory. You can then use the methods of the File class to get more information about the directory.

Knowing the current working directory is important when writing applications in Kotlin. By knowing the current working directory, you can access files and folders in your program. Knowing the current working directory also makes it easier to debug your program, since you can easily identify the location of the files and folders related to your program.

Copyright © 2022 helpful.codes

Источник

Write a Kotlin Program to Get Current Working Directory

In Kotlin, getting the current working directory is a simple task.

You can achieve this by using the System.getProperty method with the “user.dir” property.

Here’s a program that demonstrates how to get the current working directory in Kotlin:

In this program, we first use the System.getProperty method to get the value of the “user.dir” property, which represents the current working directory.

We store the value in the workingDirectory variable and then print it out to the console using the println method.

When you run this program, you should see the current working directory printed to the console.

It’s worth noting that the current working directory can vary depending on how the program is run.

For example, if you run the program from the command line, the current working directory will be the directory in which you executed the command.

If you run the program from an IDE, the current working directory will be the project directory.

In conclusion, getting the current working directory in Kotlin is a straightforward process that can be accomplished using the System.getProperty method with the “user.dir” property.

With this knowledge, you can now easily retrieve the current working directory in your Kotlin programs.

Источник

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