java.nio.file.Path with test code


port static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;
import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.junit.Before;
import org.junit.Test;
public class PathClassTest {
 @Before
 public void setUp() throws Exception {
 }
 @Test
 public void fileClassTest() {
  File file = new File("C:/Users/hdju/workspace/java7Nio2/src/test/resource/index.html");
  assertThat("index.html", is(file.getName()));
  assertThat("index.html", is(file.getName()));
 }
 @Test
 public void pathClassBasicTest() {
  Path pathFile = Paths.get("C:/Users/hdju/workspace/java7Nio2/src/test/resource/index.html");
  File file = pathFile.toFile();
  assertThat("index.html", is(file.getName()));
 }
 private String convertWindowPathToStandardPath(String windowPath) {
  if (System.getenv("OS").toLowerCase().contains("windows")) {
   windowPath = windowPath.replaceAll("\\\\", "/");
  }
  return windowPath;
 }
 @Test
 public void definingAPathTest() {
  String urlPath = "C:/Users/hdju/workspace/java7Nio2/src/test/resource/index.html";
  Path path1 = Paths.get(urlPath);
  assertThat(urlPath, is(convertWindowPathToStandardPath(path1.toFile().getPath())));
 }
 @Test
 public void pathInfomationTest() {
  String urlPath = "C:/Users/hdju/workspace/java7Nio2/src/test/resource/index.html";
  String[] urlPathArr = { "Users", "hdju", "workspace", "java7Nio2", "src", "test",
    "resource", "index.html" };
  Path path = Paths.get(urlPath);
  for (int i = 0; i < path.getNameCount(); i++) {
   assertThat(urlPathArr[i], is(path.getName(i).toString()));
  }
  assertThat("index.html", is(path.getFileName().toString()));
  assertThat("C:/", is(convertWindowPathToStandardPath(path.getRoot().toString())));
  assertThat("C:/Users/hdju/workspace/java7Nio2/src/test/resource",
    is(convertWindowPathToStandardPath(path.getParent().toString())));
  // ~ 이상 ~ 미만으로 파악하면됨.
  assertThat("Users", is(convertWindowPathToStandardPath(path.subpath(0, 1).toString())));
  assertThat("hdju/workspace", is(convertWindowPathToStandardPath(path.subpath(1, 3)
    .toString())));
 }

 @Test
 public void pathIterateTest(){
  String urlPath = "C:/Users/hdju/workspace/java7Nio2/src/test/resource/index.html";
  String[] expectedUrlPathArr = { "Users", "hdju", "workspace", "java7Nio2", "src", "test",
    "resource", "index.html" };
  Path path = Paths.get(urlPath);
  int i = 0;
  // Path 클래스는 Iterable을 구현하고 있다.
  for(Path name : path){
   assertThat(expectedUrlPathArr[i], is(name.toString()));
   i++;
  }
 }

 /**
  * TODO
  * resolve() : base uri에 파일명을 덪붙이고 싶을때
  * resolveSibling() : 특정 파일의 base uri를 찾아 그것을 다른 파일명에 덪붙이고 싶을때
  * relativize() : 두파일간의 상대 위치를 알고 싶을때
  */
}

댓글

이 블로그의 인기 게시물

Session 대신 JWT를 사용하는 이유

VSCode에서의 VIM 단축키와 키보드 구매 가이드

우분투에서 테스트링크(testlink)와 맨티스(mantis)로 테스팅 서버 구성하기