Convert String to Path in Java

In this post, we will see how to convert String to Path in Java.

Using Paths’get() method [ Java 7 ]

To convert String to Path, use jva.nio.file.Paths's get() method. It is a static method.

Here is an example:

package org.arpit.java2blog;

import java.nio.file.Path;
import java.nio.file.Paths;

public class CreatePathFromStringMain {

    public static void main(String[] args) {
        String pathStr = "C:/temp/tempFile.txt";
        // Create path from string
        Path path = Paths.get(pathStr);
        System.out.println("Path => "+path);
    }
}

Output:

Path => C:\temp\tempFile.txt

You can also join multiple strings using Paths‘s get() method. It will join all the String with delimiter /.

Here is an example:

package org.arpit.java2blog;

import java.nio.file.Path;
import java.nio.file.Paths;

public class CreatePathFromStringMain {

    public static void main(String[] args) {
        // Create path from string
        Path path = Paths.get("C:","temp","tempFile.txt");
        System.out.println("Path => "+path);
    }
}

Output:

Path => C:\temp\tempFile.txt

Using Path’s of() method [ Java 11 ]

There is new method of() introduced in Java 11 which takes String as argument and provides the Path object.
Here is an example:

package org.arpit.java2blog;

import java.nio.file.Path;

public class CreatePathFromStringMain {

    public static void main(String[] args) {
        String pathStr = "C:/temp/tempFile.txt";
        // Create path from string
        Path path1 = Path.of(pathStr);
        System.out.println("Path => "+path1);

        // Using multiple Strings
        Path path2 = Path.of("C:","temp","tempFile.txt");
        System.out.println("Path Using multiple Strings => "+path2);
    }
}

Output:

Path => C:\temp\tempFile.txt
Path Using multiple Strings => C:\temp\tempFile.txt

That’s all about how to convert String to Path in Java.

[social_share share_on="facebook,twitter,linkedin,whatsapp"][post_navigator in_same_term="true"]

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.