Java中获取当前路径

1. 获取当前路径(绝对路径)

复制代码
package p01;

import java.io.File;
import java.io.IOException;
import java.net.URL;

public class Hello01 {
    public static void main(String[] args) {
        System.out.println(getCurrentPath1());// D:\eclipseJavaWorkspace\eclipse202006Workspace\Hello\bin
        System.out.println(new Hello01().getCurrentPath2());// D:\eclipseJavaWorkspace\eclipse202006Workspace\Hello\bin\p01
        System.out.println(getCurrentPath3());// D:\eclipseJavaWorkspace\eclipse202006Workspace\Hello
        System.out.println(getCurrentPath4());// file:/D:/eclipseJavaWorkspace/eclipse202006Workspace/Hello/bin/
        System.out.println(getCurrentPath5());// D:\eclipseJavaWorkspace\eclipse202006Workspace\Hello\bin
        System.out.println(getCurrentPath6());// D:\eclipseJavaWorkspace\eclipse202006Workspace\Hello
        System.out.println(getCurrentPath7());// /D:/eclipseJavaWorkspace/eclipse202006Workspace/Hello/bin/

        /* 结果:
D:\eclipseJavaWorkspace\eclipse202006Workspace\Hello\bin
D:\eclipseJavaWorkspace\eclipse202006Workspace\Hello\bin\p01
D:\eclipseJavaWorkspace\eclipse202006Workspace\Hello
file:/D:/eclipseJavaWorkspace/eclipse202006Workspace/Hello/bin/
D:\eclipseJavaWorkspace\eclipse202006Workspace\Hello\bin
D:\eclipseJavaWorkspace\eclipse202006Workspace\Hello
D:\eclipseJavaWorkspace\eclipse202006Workspace\Hello\bin
        */
    }

    // 获取当前类的所在工程路径;
    public static String getCurrentPath1() {
        File f = new File(Hello01.class.getResource("/").getPath());
        return f.getPath();
    }

    // 获取当前类的绝对路径;
    public String getCurrentPath2() {
        File f = new File(this.getClass().getResource("").getPath());
        return f.getPath();
    }

    // 获取当前类的所在工程路径;
    public static String getCurrentPath3() {
        File directory = new File("");// 参数为空
        // getCanonicalPath()返回的就是标准的将符号完全解析的路径
        String courseFile = "";
        try {
            courseFile = directory.getCanonicalPath();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return courseFile;
    }

    // 获取当前类的所在工程路径;
    // file:/D:/eclipseJavaWorkspace/eclipse202006Workspace/Hello/bin/
    public static String getCurrentPath4() {
        URL path = Thread.currentThread().getContextClassLoader().getResource("");
        return path.toString();
    }

    public static String getCurrentPath5() {
        return System.getProperty("java.class.path");
    }

    public static String getCurrentPath6() {
        return System.getProperty("user.dir");
    }

    public static String getCurrentPath7() {
        String path = Thread.currentThread().getContextClassLoader().getResource("").getPath();// /D:/eclipseJavaWorkspace/eclipse202006Workspace/Hello/bin/
        String p = new File(path).getAbsolutePath();// D:\eclipseJavaWorkspace\eclipse202006Workspace\Hello\bin
        return p;
    }

}
View Code
复制代码

 2. 获取资源文件的路径,或读文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
获取src下资源文件编译后的路径(即classes路径):
String s2 = Thread.currentThread().getContextClassLoader().getResource("").getPath();        //   /D:/eclipseJavaWorkspace/eclipse202006Workspace/Hello/bin/
//String s3 = Thread.currentThread().getContextClassLoader().getResource("/").getPath();// java工程下报错:NullPointerException
String s4 = Thread.currentThread().getContextClassLoader().getResource("test.txt").getPath();//   /D:/eclipseJavaWorkspace/eclipse202006Workspace/Hello/bin/test.txt
或者        类名.class.getClassLoader().getResource("").getPath();
或者        this.class.getClassLoader().getResource("").getPath();
 
//此方法获得的path,虽然前面多一个“/”,但仍然可以用于构造File
File file2 = new File(s2);
File file4 = new File(s4);
InputStream in = new BufferedInputStream(new FileInputStream(new File(s2)));
 
//还可以 使用如下,直接返回输入流对象
InputStream resourceAsStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("test.txt");//test.txt在src夹下(即classpath下)
if(null == resourceAsStream) {
    throw new RuntimeException("nullPointer...");
}
else {
    StringBuilder sb = new StringBuilder();
    byte[] buf = new byte[512];
    int len = -1;
    try {
        while((len = resourceAsStream.read(buf))!=-1) {
            sb.append(new String(buf,0,len));
        }
        System.out.println(sb.toString());
    } catch (IOException e) {
        e.printStackTrace();
    }
}

 3. Java中的getResourceAsStream有以下几种:

  • 1. Class.getResourceAsStream(String path) : path 不以’/'开头时默认是从此类所在的包下取资源,以'/'开头则是从ClassPath根下获取。其只是通过path构造一个绝对路径,最终还是由ClassLoader获取资源。
  • 2. Class.getClassLoader.getResourceAsStream(String path) :默认则是从ClassPath根下获取,path不能以’/'开头,最终是由ClassLoader获取资源。
  • 3. ServletContext. getResourceAsStream(String path):默认从WebAPP根目录下取资源,Tomcat下path是否以’/'开头无所谓,当然这和具体的容器实现有关。
  • 4. Jsp下的application内置对象就是上面的ServletContext的一种实现。
posted @   htj10  阅读(2456)  评论(0编辑  收藏  举报
编辑推荐:
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
TOP
点击右上角即可分享
微信分享提示