Converting a relative path into an absolute path - Java File Path IO

Java examples for File Path IO:Path

Description

Converting a relative path into an absolute path

Demo Code

import java.net.URI;
import java.net.URISyntaxException;
import java.nio.file.FileSystems;
import java.nio.file.InvalidPathException;
import java.nio.file.Path;
import java.nio.file.Paths;

public class Main {
  public static void main(String[] args) {
    String separator = FileSystems.getDefault().getSeparator();
    System.out.println("The separator is " + separator);
    try {/*from   w ww  . j av a2  s  .  com*/
      Path path = Paths.get(new URI("file:///C:/home/docs/users.txt"));
      System.out.println("subpath: " + path.subpath(0, 3));
      path = Paths.get("/home", "docs", "users.txt");
      System.out.println("Absolute path: " + path.toAbsolutePath());
      System.out.println("URI: " + path.toUri());
    } catch (URISyntaxException ex) {
      System.out.println("Bad URI");
    } catch (InvalidPathException ex) {
      System.out.println("Bad path: [" + ex.getInput() + "] at position"
          + ex.getIndex());
    }
  }
}

Related Tutorials