---
title: "Java类中的文件路径"
author: "lectery"
date: "2010-05-05T16:29:12Z"
tags: []
categories: ["编程语言"]
slug: "java"
draft: false
lastmod: "2010-05-07T13:25:02Z"
id: 659667
url: "https://lectery.iteye.com/blog/659667"
---

很多时候程序需要读取工程中的一些文件（如xml、properties等等），而文件的路径指定往往会困扰我们的开发工作，尤其在web程序的开发中路径问题尤为突出，下面就简单介绍一下java中相对路径的获得方法。

1. getRealPath()：仅限使用在servlet中，可以动态获得文件的绝对路径，部署在服务器上的工程通常要查看部署后服务器中的路径。
   
   ```
   this.getServletContext().getRealPath("WEB-INF/classes/com.demo/config.xml")
   ```
2. getResource/getResourceAsStream:
   
   ```
   String path =”/xml/config.xml”; 
   String fullPath=this.getClass().getClassLoader().getResource(path).getPath(); 
   ```
   
    或是
   
   ```
   Class.class.getResource("/file/config.xml").getPath()
   ```

    采纳了 [seaizon](http://seaizon.iteye.com) 的建议：

seaizon 写道

在使用Class.getResource/Class.getResourceAsStream 时， 资源路径有两种方式， 一种以 / 开头，则这样的路径是指定绝对路径， 如果不以 / 开头， 则路径是相对与这个class所在的包的。

在使用ClassLoader.getResource/ClassLoader.getResourceAsStream时， 路径直接使用相对于classpath的绝对路径。