java获取的一些路径

我的工程目录放在D:\Eclipse Workspace\TankeWar4,下面不再具体说明。

A类名.class.getResource(“”)方法是获得A类当前生成的class文件绝对路径;返回的路径内容最后包含‘/’

//示例代码

public static void   getFilePath()  
     {  
          //MyTanKeGame4.class.getResource()
          //方法获得MyTanKeGame4类当前生成的class文件的的绝对路径
          //每个类都有一个class属性
          String path = MyPanel.class.getResource("").toString();  
          System.out.println(path);

          if (path != null)  
        {  
              path = path.substring(6, path.indexOf("WEB-INF") + 8);//如果是windwos将5变成6   
              //System.out.println("current path :" + path);   
        }  
//        return (path + fileName);  
     }  

输出结果是:file:/D:/Eclipse%20Workspace/TankeWar4/bin/com/TankeWar4/
PS:%20表示的是空格


利用System.getProperty()函数获取当前路径,得到项目文件夹的根目录,不带/

//返回java工程目录,即项目文件夹的根目录;
测试返回:D:\Eclipse Workspace\TankeWar4;这是我测试的java工程存放目录
System.out.println(System.getProperty("user.dir"));

//使用File类提供的方法获取当前工程目录

//使用File提供的函数获取当前路径
File directory = new File("");//设定为当前文件夹    
try {           System.out.println(directory.getCanonicalPath());//获取标准的路径    
System.out.println(directory.getAbsolutePath());//获取绝对路径    
    } catch (IOException e) 
    {
            // TODO Auto-generated catch block
            e.printStackTrace();
    }

最后输出结果是:

D:\Eclipse Workspace\TankeWar4
D:\Eclipse Workspace\TankeWar4

getClass().getResource() 方法获得相对路径

public  void getCurrentPath()
    {  
      //取得根目录路径  ,getClass适用于对象获取对象的类的一些信息。
    String rootPath=this.getClass().getResource("/").getFile().toString();  
    System.out.println("rootPath =\t" +rootPath);
//当前目录路径   
    String currentPath1=this.getClass().getResource(".").getFile().toString();  
        System.out.println("currentPath1 =\t" +currentPath1);
        String currentPath2=this.getClass().getResource("").getFile().toString();  
        System.out.println("currentPath2 =\t" +currentPath2);
        //当前目录的上级目录路径   
        String parentPath=this.getClass().getResource("../").getFile().toString();  
        System.out.println("parentPath =\t" +parentPath);    


    } 

最后测试的结果是:

rootPath =  /D:/Eclipse%20Workspace/TankeWar4/bin/
currentPath1 =  /D:/Eclipse%20Workspace/TankeWar4/bin/com/TankeWar4/
currentPath2 =  /D:/Eclipse%20Workspace/TankeWar4/bin/com/TankeWar4/
parentPath =    /D:/Eclipse%20Workspace/TankeWar4/bin/com/

也是看到getResource方法不同的参数有不同的返回值。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值