使用
File
类,
newFile(String
fileName
)
l
在
Servlet
中使用
getRealPath
(String
str
)
方法动态地获得文件的
绝对路径
l
使用
Class.getResource
()
方法
l
使用
Class.getResourceAsStream
()
方法
l
方法一:
Filefile3 = new File(
Test.class.getResource
("file3.txt").
getFile
());
l
方法二:
Filefile3 = new File(
Test.class.getResource
("/
javaapplication
/file3.txt").
getFile
());
l
方法三:
Filefile3 = new File(
Test.class.getClassLoader
().
getResource
("
javaapplication
/file3.txt").
getFile
());
l
方法一:
Filefile4 = new File(
Test.class.getResource
("/file4.txt").
getFile
());
l
方法二:
Filefile4 = new File(
Test.class.getClassLoader
().
getResource
("file4.txt").
getFile
());
l
file1.txt
与
file2.txt
文只能使用绝对路径
l
不能像
file3.txt
与
file4.txt
一样用
class.getResource
()
这种方法获得
l
假如整个
project
目录放在
c:/
下,
file1
与
file2
的获取方法分别为:
¡
File file1 = newFile("c:/project/src/myapp/file1.txt");
¡
File file2 = newFile("c:/project/src/file2.txt");
l
想获得文件
,
需要从最终生成的
.
class文件为着手点,不要以.java文件的路径为出发点,因为真正使用的是.class,不会拿个.java文件就使用
l
至于
getResouce
()
方法的参数,以
class
为出发点,再结合相对路径的概念,就可以准确地定位资源文件了
关于
getResourceAsStream
()
方法,参数是与
getResouce
()
方法是一样的,它相当于你用
getResource
()
取得
File
文件后,再
new
InputStream
(file)
一样的结果
l
用
Class.getResourceAsStream
()
时,路径应该是以
“/”
开头的,如:
mypackage.Hello.class.getResourceAsStream ("/ config /config.ini");
mypackage.Hello.class.getResourceAsStream ("/ config /config.ini");
l
用
ClassLoader
的
getResourceAsStream
()
, 不用以
“/”
开头。如:
mypackage.Hello.class.getClassLoader.getResourceAsStream (" config /config.ini");
mypackage.Hello.class.getClassLoader.getResourceAsStream (" config /config.ini");
l
注意文件放置的位置,应该放在
classpath
下。如:工程文件中的
classes
下