piumnl
1/2/2017 - 2:59 AM

for java.nio.file.Path

for java.nio.file.Path

import org.junit.Assert;
import org.junit.Test;

import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * 路径操作
 *
 * @author piumnl
 * @version 1.0.0
 * @since on 2016-12-29.
 */
public class PathDemo {

  @Test
  public void test_get(){
    Path path = Paths.get("D:", "game");
    System.out.println(path);
    
    Path two = Paths.get("D:/", "//gam\\e");
    System.out.println(two);
    
    String property = System.getProperty("user.dir");
    Path path = Paths.get(property);
    System.out.println(path);
  }

  @Test
  public void test_resolve() throws MalformedURLException, URISyntaxException {
    Path windows = Paths.get("C:", "Windows");
    Path music = windows.resolve(Paths.get("D:", "music"));
    Assert.assertEquals("D:\\music", music.toString());

//    不能这样写,因为 http 不是一种文件系统,这是一种 资源定位标识 。类似还有ftp等。
//    URI uri = new URL("https", "localhost", 8080, "index.html").toURI();
//    Path resolve = windows.resolve(Paths.get(uri));
//    System.out.println(resolve);

    Path resolve = windows.resolve(Paths.get("Apache", "Tomcat"));
    Assert.assertEquals("C:\\Windows\\Apache\\Tomcat",resolve.toString());

    Path game = Paths.get("game");
    Path dmc = game.resolve("Devil May Cry").resolve("bin");
    Assert.assertEquals("game\\Devil May Cry\\bin", dmc.toString());
  }

  @Test
  public void test_resolveSibling(){
    Path doc = Paths.get("D:", "doc");
    Path music = doc.resolveSibling("music");
    Assert.assertEquals("D:\\music", music.toString());
  }

  @Test
  public void test_normalize(){
    Path path = Paths.get("D:\\abc/../game/fef").normalize();
    Assert.assertEquals("D:\\game\\fef", path.toString());
  }

  @Test
  public void test_relativize(){
    Path master = Paths.get("C:\\home\\piumnl");
    Path secondary = Paths.get("C:\\home\\lin\\myprog");
    Path relativize = master.relativize(secondary);
    Assert.assertEquals("..\\lin\\myprog", relativize.toString());
  }

  @Test
  public void test_other(){
    Path filePath = Paths.get("E:", "music", "myVoice.mp3");
    Assert.assertEquals("E:\\", filePath.getRoot().toString());
    Assert.assertEquals("E:\\music", filePath.getParent().toString());
    Assert.assertEquals("myVoice.mp3", filePath.getFileName().toString());
    Assert.assertEquals(FileSystems.getDefault(), filePath.getFileSystem());
  }

}