java 获取当前文件(项目)路径的多种方式

 
第一种:  

File f = new File(this.getClass().getResource("/").getPath()); 
System.out.println(f); 
结果: 
C:\Documents%20and%20Settings\Administrator\workspace\projectName\bin 
获取当前类的所在工程路径; 
如果不加“/” 
File f = new File(this.getClass().getResource("").getPath()); 
System.out.println(f); 
结果: 
C:\Documents%20and%20Settings\Administrator\workspace\projectName\bin\com\test 
获取当前类的绝对路径; 

第二种: 
File directory = new File("");//参数为空 
String courseFile = directory.getCanonicalPath() ; 
System.out.println(courseFile); 
结果: 
C:\Documents and Settings\Administrator\workspace\projectName 
获取当前类的所在工程路径; 

第三种: 
URL xmlpath = this.getClass().getClassLoader().getResource("selected.txt"); 
System.out.println(xmlpath); 
结果: 
file:/C:/Documents%20and%20Settings/Administrator/workspace/projectName/bin/selected.txt 
获取当前工程src目录下selected.txt文件的路径 

第四种: 
System.out.println(System.getProperty("user.dir")); 
结果: 
C:\Documents and Settings\Administrator\workspace\projectName 
获取当前工程路径 

第五种: 
System.out.println( System.getProperty("java.class.path")); 
结果: 
C:\Documents and Settings\Administrator\workspace\projectName\bin 

获取当前工程路径

通过代码获取jar中的资源,这里就不能path了,要用InputStream:

InputStream inputStream = this.getClass().getResourceAsStream(fileName);

### 回答1: 你可以使用Java中的File类来获取当前路径的绝对路径。具体代码如下: ``` File file = new File(""); String absolutePath = file.getAbsolutePath(); System.out.println("当前路径的绝对路径是:" + absolutePath); ``` 执行该代码后,控制台会输出当前路径的绝对路径。 ### 回答2: 在Java中,我们可以使用`System.getProperty("user.dir")`来获取当前工作目录的绝对路径。 `System.getProperty()`方法用于获取系统属性,默认情况下,它返回键值对的列表。其中,`"user.dir"`是一个系统属性,它表示用户的当前工作目录。 例如,假设我们的Java程序位于路径`/Users/username/Documents/JavaProgram`中,并且我们想要获取当前工作目录的绝对路径。 我们可以使用以下代码来获取当前工作目录的绝对路径: ```java String currentDir = System.getProperty("user.dir"); System.out.println("当前工作目录的绝对路径为:" + currentDir); ``` 运行该程序,我们将会得到输出:`当前工作目录的绝对路径为:/Users/username/Documents/JavaProgram`。 通过调用`System.getProperty("user.dir")`方法,我们可以获取当前路径的绝对路径当前路径指的是程序运行时所在的目录。 ### 回答3: 在Java获取当前路径的绝对路径多种方法。我将介绍两种常用的方法: 方法一: 可以使用`System.getProperty("user.dir")`方法来获取当前路径的绝对路径。该方法返回一个字符串,表示当前工作目录的路径。示例如下: ```java String currentPath = System.getProperty("user.dir"); System.out.println("当前路径的绝对路径是:" + currentPath); ``` 方法二: 还可以使用`File`类来获取当前路径的绝对路径。首先需要创建一个`File`对象,传入一个文件或目录的相对路径作为参数。然后使用`getAbsolutePath()`方法获取文件或目录的绝对路径。示例如下: ```java File file = new File("."); String currentPath = file.getAbsolutePath(); System.out.println("当前路径的绝对路径是:" + currentPath); ``` 这两种方法都能够获取当前路径的绝对路径,具体使用哪种方法取决于你的需求和编程风格。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值