Java中获取当前路径

摘要:
1.获取当前路径(绝对路径)package01;importjava.io。文件importjava.io。IOException;导入java.net。URL;publicclassHello01{publicstaticvoidmain(String[]args){System.out.println(getCurrentPath1());//D:eclipseJavaWork

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

Java中获取当前路径第1张Java中获取当前路径第2张
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:eclipseJavaWorkspaceeclipse202006WorkspaceHelloin
        System.out.println(new Hello01().getCurrentPath2());// D:eclipseJavaWorkspaceeclipse202006WorkspaceHelloinp01
        System.out.println(getCurrentPath3());// D:eclipseJavaWorkspaceeclipse202006WorkspaceHello
        System.out.println(getCurrentPath4());// file:/D:/eclipseJavaWorkspace/eclipse202006Workspace/Hello/bin/
        System.out.println(getCurrentPath5());// D:eclipseJavaWorkspaceeclipse202006WorkspaceHelloin
        System.out.println(getCurrentPath6());// D:eclipseJavaWorkspaceeclipse202006WorkspaceHello
        System.out.println(getCurrentPath7());// /D:/eclipseJavaWorkspace/eclipse202006Workspace/Hello/bin/

        /* 结果:
D:eclipseJavaWorkspaceeclipse202006WorkspaceHelloin
D:eclipseJavaWorkspaceeclipse202006WorkspaceHelloinp01
D:eclipseJavaWorkspaceeclipse202006WorkspaceHello
file:/D:/eclipseJavaWorkspace/eclipse202006Workspace/Hello/bin/
D:eclipseJavaWorkspaceeclipse202006WorkspaceHelloin
D:eclipseJavaWorkspaceeclipse202006WorkspaceHello
D:eclipseJavaWorkspaceeclipse202006WorkspaceHelloin
        */
    }

    // 获取当前类的所在工程路径;
    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:eclipseJavaWorkspaceeclipse202006WorkspaceHelloin
        return p;
    }

}
View Code

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

获取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的一种实现。

免责声明:文章转载自《Java中获取当前路径》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇adb命令大全端游数值设计思路流程下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

php Redis函数使用总结(string,hash,list, set , sort set )

  对于:string, set , sort set , hash 的增,改操作,是同一个命令,但是把它当改操作时,及时成功返回值依旧为0 对于:list结构来说,增删改查自有一套方法。   1 <?php 2 /*1.Connection*/ 3 $redis = new Redis(); 4 $redis-...

在ASP.NET WebAPI 中使用缓存【Redis】

初步看了下CacheCow与OutputCache,感觉还是CacheOutput比较符合自己的要求,使用也很简单 PM>Install-Package Strathweb.CacheOutput.WebApi2 基础使用 CacheOutput特性 [Route("get")] [CacheOutput(Cli...

C#下的BMP图像压缩类

这几天研究比较多,其中一个成果就是下面这个图像压缩类。可以把BMP文件压成任意质量的JPEG,在.net framework 2.0下编译通过。有时间的话我会把它写成可以压缩其他格式的类,其实改一下参数就可以了。 时间原因没有写注释,(不过这个类真够简单了)还是介绍一下吧: 只有一个没有重载的构造函数,参数是待压缩BMP文件的路径,还有一个长整形的质量参数...

Delphi声明Record变量后直接初始化

 TARec = record    A1: string;    A2: string;  end;   TBRec = record    A1: string;    A2: string;    ARec: TARec;  end;   PAppWindow = ^TAppWindow;  TAppWindow = Record    Width,...

[Android Exception 1A] -com.android.volley.NoConnectionError: java.io.InterruptedIOException

12-24 14:21:47.470 24220-24220/com.tongyan.tutelage W/System.err: com.android.volley.NoConnectionError: java.io.InterruptedIOException 12-24 14:21:47.470 24220-24220/com.tongyan....

C# 反射(Reflection)

反射(Reflection)可以在运行时获 得.NET中每一个类型(包括类、结构、委托、接口和枚举等)的成员,包括方法、属性、事件,以及构造函数等。 反射用到的命名空间:    System.Reflection    System.Type    System.Reflection.Assembly using System; using System...