java web中读取文件,相对路径怎么写

Python010

java web中读取文件,相对路径怎么写,第1张

相对路径的话,可以先获取到当前文件的编译路径,之后在找到想找文件的路径的思路来实现。

举例:

XMLS.class.getClass().getResourceAsStream("/test/test.txt")

解释:XMLS.class.getClass()是获取当前的类编译路径,之后通过getResourceAsStream的形式即可找到要读取的文件的路径。

备注:这个方法中后面的路径也可以通过截取的形式来进行路径获取,实现原理都是找到当前类路径,之后通过相对位置找到另外文件路径。

1. 使用java.lang.Class类的getResourceAsStream(String name)方法 InputStream in = getClass().getResourceAsStream("/config.properties")

在静态方法中,由于不能使用getClass()方法,必须写出类的名字。区别不大。

MyClass.class.getResourceAsStream("/config.properties")

使用这个方法,路径前面可以加斜杠也可以不加。根据Class类getResourceAsStream()方法的JavaDoc:

Finds a resource with a given name.  The rules for searching resources associated with a given class are implemented by the defining  class loader of the class.  This method delegates to this object's class loader.  If this object was loaded by the bootstrap class loader, the method delegates to ClassLoader.getSystemResourceAsStream.

Before delegation, an absolute resource name is constructed from the given resource name using this algorithm:

If the name begins with a '/' ('\u002f'), then the absolute name of the resource is the portion of the name following the '/'.

Otherwise, the absolute name is of the following form:

modified_package_name/name

Where the modified_package_name is the package name of this object with '/' substituted for '.' ('\u002e').

就是说,这个path假如以斜杠开头,则斜杠后面的部分是文件相对classpath的路径;假如不是,Java会把这个path看作是“包名/文件名”的结构,会尝试在这个类的包里面去找,而不是从classpath开始找;在这种情况下,除非你把properties文件放到MyClass.class所属的包里面,不然都会是null的。

2. 使用java.lang.ClassLoader类的getResourceAsStream(String name)方法 路径是不能加斜杠的!非常重要。

MyClass.class.getClassLoader().getResourceAsStream("config.properties")

这是因为使用classloader进行读取,所输入的参数必须是一个相对classpath的绝对路径,在格式上,一个绝对路径是不能以'/'开头的。

注意这两个方法是同名的,但路径参数的格式截然不同。

3. 在Maven中的运用

现在几乎所有的web project都是maven project,Maven的默认设置是把

src/main/resources/

加入到classpath里面的。那么,最好的做法是把你的properties文件放进src/main/resources里面,然后用上面代码读取。用Class类的,一般要加斜杠;用ClassLoader类的,绝不能加斜杠!

假如是Eclipse里面,需要把这个src/main/resources加到classpath里面。具体操作是右击工程,选择“Configure buildpath”,根据Maven的要求,把src/main/java和src/main/resources都加进去,并且保证Exclude是none,Include是all,或者至少要包括你需要读取的文件。

项目迁移的过程中发现以前的代码维护性实在是差。

我把问题简化为以下这些简单的代码:

项目M

引用了项目

A.jar,这个A在lib目录里面

在A里面放置了一个配置文件test.properties,

就放在jar的根目录下。

A.jar

|___test.properties

在M中有一段代码回去读取这个A.jar里的配置文件,简单一点就用下面这句话来调用。

Java

code

public

class

ConfigUtil

{

public

static

String

getInstance()

throws

Exception{

String

path

=

ConfigUtil.class.getResource("/").toString()

path

=

path.substring(0,

path.length()-8)//

System.out.println(path)//这里打印的结果显示可以拿到当前类的绝对路径

InputStream

f

=

new

FileInputStream("jar:"+path+"lib!/A.jar/"+"test.properties")

return

"xxx"

}

}