classpath和filepath

********************************

java中的相对路径和绝对路径

********************************

 

相对路径(其实就是编译后的路径)

——类路径:当前类所在的路径。不添加“/”则表示类加载的路径

@Test
public void classPath() {
   // 通过获取当前类的编译后所在的路径 URL classPath = getClass().getResource(""); System.out.println("classPath = " + classPath); }
// 输出:classPath = file:/F:/etom/pmms/target/test-classes/test/

 

——当前类所在的根路径,添加“/”表示类加载的根路径

@Test
public void classRootPath() {
    URL classRootPath= getClass().getResource("/");
    System.out.println("classRootPath= " + classRootPath);
}
// classRootPath= file:/F:/etom/pmms/target/test-classes/

 

——项目工程所在的根路径

@Test
public void rootPath() throws IOException {
    File file = new File("");
    if (!file.exists()) {
        file.mkdirs();
    }
    String rootPath = file.getCanonicalPath();
    System.out.println("rootPath = " + rootPath);
}
// rootPath = F:\etom\pmms

 

——当前线程的类加载器获取所在的路径

@Test
public void threadPath() {
   // 通过线程的加载类所在的路径 URL threadPath = Thread.currentThread().getContextClassLoader().getResource(""); System.out.println("threadPath = " + threadPath); }
// 输出:threadPath = file:/F:/etom/pmms/target/test-classes/

 

——web的相对路径

public void webPath(HttpServletRequest request) {
   // 通过获取web上下文来获取web的相对路径 String webappPath = request.getServletContext().getRealPath(""); }

 

绝对路径

public void filePath() {
   // 直接配置文件路径即可,记住:是全路径 File file = new File("F:/etom/pmms/target/test-classes/test/"); if (!file.exists()) { file.mkdirs(); } }

 

posted @ 2018-02-05 10:22  antlord  阅读(1532)  评论(0编辑  收藏  举报