---
title: "JAVA 代码中常用文件路径获取方式"
author: "TimerBin"
date: "2013-11-07T18:04:11Z"
tags: []
categories: ["编程语言"]
slug: "java"
draft: false
lastmod: "2014-07-16T17:51:41Z"
id: 1972745
url: "https://timerbin.iteye.com/blog/1972745"
---

**前言**

 

   在java中经常会遇到读取各种不同路径下的文件内容信息，以下就是我在使用过程中所遇到的读取不同路径下文件的总结。

 

**一、本地系统盘符下的绝对路径的文件**

```
System.out.println(new File("D:/message.properties").getAbsolutePath());
System.out.println(new File("D:/message.properties").getCanonicalPath());
```

 

获得本地系统D盘下的message.properties文件内容，两种方法都可以读到配置文件内容，它们的区别在对绝对路径文件读取上是不体现的，它们的区别在于对系统盘符中的相对路径的读取上。其中getAbsolutePath()不会将路径中的“./”或者“../”进行解析，getCanonicalPath();会将路径中的“./”或者“../”进行解析成为相应路径。

详细请参考：[http://www.blogjava.net/dreamstone/archive/2007/08/08/134968.html](http://www.blogjava.net/dreamstone/archive/2007/08/08/134968.html)

 

**二、本地系统盘符下的相对路径**

```
System.out.println(new File("").getCanonicalPath());
```

 

//在java文件中运行此代码的话可以获得此java文件所在的项目所在磁盘中的路径信息(只到项目名称)，路径只到项目名称就结束了。

例子：D:\\Eclipse\\src\\HelloWord

```
System.out.println(new File("").getAbsolutePath());
```

 

//此时的getAbsolutePath()方法也可以获得到项目的所在磁盘中的路径信息与getCanonicalPath()方法返回的一致。

```
System.out.println(new File("../../").getCanonicalPath());
```

 

//在同一个文件下运行上面内容就表示此项目本地磁盘目录上后退两个目录结构地址

例子：D:\\Eclipse 也就是这个地址

```
System.out.println(new File("../../").getAbsolutePath());
```

 

//此时getAbsolutePath获得路径就与getCanonicalPath完全不同了，因为它无法识别"./"和"../"信息

例子：D:\\Eclipse\\src\\HelloWord\\..\\..但它并不报错，但如果去读取后退两个目录结构地址的文件内容时它就会报出错误信息

 

**三、ClassPath下的相对路径**

```
 System.out.println(HelloWord.class.getResource("").getFile());
 System.out.println(this.class.getResource("").getFile());
```

 

//获得HelloWord类所编译后class所存放的地址

例子：D:/Eclipse/src/HelloWord/WEB-INF/classes/com

 

```
System.out.println(HelloWord.class.getResource("../").getFile());
System.out.println(this.class.getResource("../").getFile());
```

 

//获得HelloWord类所编译后class所存放的地址的后退到上一级目录

例子：D:/Eclipse/src/HelloWord/WEB-INF/classes   **注意这里只能到这一层不可以再次向上后退**

```
 System.out.println(Thread.currentThread().getContextClassLoader().getResource(""));
```

 

//直接到当前项目的classPasth根目录下但他会在路径的前方加上file:标识

例子：file:/D:/Eclipse/src/HelloWord/WEB-INF/classes

 

```
System.out.println(Thread.currentThread().getContextClassLoader().getResource("../"));
```

 

//此用法是错误，无法在classes目录退后到上一级目录

 

**注：**在java的jar包中的类使用HelloWord.class.getResource(“").getFile()来对文件进行获取路径时会在项目上加上.jar

例子：file:/D:/HelloWord.jar!/com

**注：**在项目中引入的Jar包中可以使用ResourceBundle直接获得项目中定义的配置文件。这里不可以识别../和./标识符使用

ResourceBundle.getBundle("配置文件名称");