Java中获取当前目录

//获取当前类文件所在包的根目录

System.out.println(System.getProperty("user.dir").replace("\\","/"));

//获取当前类文件所在的目录

System.out.println(TestUpload.class.getResource("").getPath().replaceAll("%20"," "));

说明:
1.前者得到的是所在包的根目录,注意后者得到的是类编译后的 .class 所在的目录。即路径中含有 /bin/......
2.前者得到的路径中,如果有空格,会正常显示,而后者得到的路径中,如果有空格,则显示为 %20,故应使用 .replaceAll("%20", " "); 否则,会报“找不到系统路径”的错误。
3.如果是想要获得已打成可运行jar包后,jar包所在的目录,应当使用前者。但是要注意前者得到的路径末尾不带"/",如果需要,手动加上,而后者末尾带有"/"

File file = new File(" ");

String path = file.getCanonicalPath();

示例:

package com.tuz;

import java.io.File;

public class CurrentDirectory {

      public static void print(Object o) {

           System.out.println(o);

      }

      public static void main(String[] args) throws Exception {

           print(Thread.currentThread().getContextClassLoader().getResource(""));

           print(CurrentDirectory.class.getClassLoader().getResource(""));

           print(ClassLoader.getSystemResource(""));

           print(CurrentDirectory.class.getResource(""));

           print(CurrentDirectory.class.getResource("/"));

           print(new File("").getAbsolutePath());

           print(System.getProperty("user.dir"));

      }

}   

上面的例子中有的输出的是URL,可以继续转换为想要的路径名

通用方法:

              URL   url = PathTest.class.getClassLoader().getResource("1.txt");

              String path = url.getPath();

              File f = new File(path);

              System.out.println(f.getAbsolutePath());           

 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值