zoukankan      html  css  js  c++  java
  • java里getPath、 getAbsolutePath、getCanonicalPath的区别


    File的这三个方法在api中都有说明,仅以程序为例说明。

    package test;

    import java.io.File;
    import java.io.IOException;

    public class TestFilePath {

     
     public static void main(String[] args) {
      // TODO Auto-generated methodstub

      System.out.println(System.getProperty("user.dir"));
      
      try {
       System.out.println("-----默认相对路径:取得路径不同------");
       File file1 =new File("..\src\test1.txt");
       System.out.println(file1.getPath());
       System.out.println(file1.getAbsolutePath());
       System.out.println(file1.getCanonicalPath());
       System.out.println("-----默认相对路径:取得路径不同------");
       File file =new File(".\test1.txt");
       System.out.println(file.getPath());
       System.out.println(file.getAbsolutePath());
       System.out.println(file.getCanonicalPath());
       
       System.out.println("-----默认绝对路径:取得路径相同------");
       File file2 =new File("D:\workspace\test\test1.txt");
       System.out.println(file2.getPath());
       System.out.println(file2.getAbsolutePath());
       System.out.println(file2.getCanonicalPath());
      } catch (IOException e) {
       // TODOAuto-generated catch block
       e.printStackTrace();
      }
     }

    }

    程序执行结果如下:

    F:eclipseworkspace estejb
    -----默认相对路径:取得路径不同------
    ..src est1.txt
    F:eclipseworkspace estejb..src est1.txt
    F:eclipseworkspacesrc est1.txt
    -----默认相对路径:取得路径不同------
    . est1.txt
    F:eclipseworkspace estejb. est1.txt
    F:eclipseworkspace estejb est1.txt
    -----默认绝对路径:取得路径相同------
    D:workspace est est1.txt
    D:workspace est est1.txt
    D:workspace est est1.txt
    结论:

    当输入为绝对路径时,返回的都是绝对路径。

    当输入为相对路径时:

    getPath()返回的是File构造方法里的路径,是什么就是什么,不增不减

    getAbsolutePath()返回的其实是user.dir+getPath()的内容,从上面F:eclipseworkspace estejb、F:eclipseworkspace estejb..src est1.txt、F:eclipseworkspace estejb. est1.txt可以得出。

    getCanonicalPath()返回的就是标准的将符号完全解析的路径
















  • 相关阅读:
    PHP底层工作原理
    php WebSocket 简单实现demo
    php部署调优
    php简单随机实现发红包程序
    在Android中调用USB摄像头
    在addroutes后,$router.options.routes没有更新的问题(手摸手,带你用vue撸后台 读后感)
    Vue+elementUI开发中 Cannot read property 'resetFields' of undefined 问题解决以及原因分析
    如何在debug vue-cli建立的项目
    在Node.js使用Promise的方式操作Mysql(续)
    express框架中如何只执行一次res响应操作
  • 原文地址:https://www.cnblogs.com/liulaolaiu/p/11744664.html
Copyright © 2011-2022 走看看