请问在java swing绝对布局里我用fileinputstream提取的文件路径是绝对路径,有什么方法写成相对路径,在封装成ja

1628人阅读
技术学习(71)
1.如何获得当前文件路径
字符串类型:System.getProperty(&user.dir&);
package com.zcjl.test.
import java.io.F
public class Test {
&&& public static void main(String[] args) throws Exception {
&&&&&&& System.out.println(
&&&&&&&&&&& Thread.currentThread().getContextClassLoader().getResource(&&));
&&&&&&& System.out.println(Test.class.getClassLoader().getResource(&&));
&&&&&&& System.out.println(ClassLoader.getSystemResource(&&));
&&&&&&& System.out.println(Test.class.getResource(&&));
&&&&&&& System.out.println(Test.class.getResource(&/&));
&&&&&&& System.out.println(new File(&&).getAbsolutePath());
&&&&&&& System.out.println(System.getProperty(&user.dir&));
2.Web服务中
(1).Weblogic
WebApplication的系统文件根目录是你的weblogic安装所在根目录。
例如:如果你的weblogic安装在c:\bea\weblogic700.....
那么,你的文件根路径就是c:\.
所以,有两种方式能够让你访问你的服务器端的文件:
a.使用绝对路径:
比如将你的参数文件放在c:\yourconfig\yourconf.properties,
直接使用 new FileInputStream(&yourconfig/yourconf.properties&);
b.使用相对路径:
相对路径的根目录就是你的webapplication的根路径,即WEB-INF的上一级目录,将你的参数文件放在yourwebapp\yourconfig\yourconf.properties,
这样使用:
new FileInputStream(&./yourconfig/yourconf.properties&);
这两种方式均可,自己选择。
(2).Tomcat
在类中输出System.getProperty(&user.dir&);显示的是%Tomcat_Home%/bin
不是你的JSP放的相对路径,是JSP引擎执行这个JSP编译成SERVLET
的路径为根.比如用新建文件法测试File f = new File(&a.htm&);
这个a.htm在resin的安装目录下
(4).如何读相对路径哪?
在Java文件中getResource或getResourceAsStream均可
例:getClass().getResourceAsStream(filePath);//filePath可以是&/filename&,这里的/代表web发布根路径下WEB-INF/classes
(5).获得文件真实路径
string& file_real_path=request.getRealPath(&mypath/filename&);&
通常使用request.getRealPath(&/&);&
3.文件操作的类
import java.io.*;
import java.net.*;
import java.util.*;
//import javax.swing.filechooser.*;
//import org.jr.swing.filter.*;
* 此类中封装一些常用的文件操作。
* 所有方法都是静态方法,不需要生成此类的实例,
* 为避免生成此类的实例,构造方法被申明为private类型的。
* @since& 0.1
public class FileUtil {
&& * 私有构造方法,防止类的实例化,因为工具类不需要实例化。
& private FileUtil() {
&& * 修改文件的最后访问时间。
&& * 如果文件不存在则创建该文件。
&& * &b&目前这个方法的行为方式还不稳定,主要是方法有些信息输出,这些信息输出是否保留还在考
虑中。&/b&
&& * @param file 需要修改最后访问时间的文件。
&& * @since& 0.1
& public static void touch(File file) {
&&& long currentTime = System.currentTimeMillis();
&&& if (!file.exists()) {
&&&&& System.err.println(&file not found:& + file.getName());
&&&&& System.err.println(&Create a new file:& + file.getName());
&&&&& try {
&&&&&&& if (file.createNewFile()) {
&&&&&&& //& System.out.println(&Succeeded!&);
&&&&&&& else {
&&&&&&& //& System.err.println(&Create file failed!&);
&&&&& catch (IOException e) {
&&&&& //& System.err.println(&Create file failed!&);
&&&&&&& e.printStackTrace();
&&& boolean result = file.setLastModified(currentTime);
&&& if (!result) {
&&& //& System.err.println(&touch failed: & + file.getName());
&& * 修改文件的最后访问时间。
&& * 如果文件不存在则创建该文件。
&& * &b&目前这个方法的行为方式还不稳定,主要是方法有些信息输出,这些信息输出是否保留还在考
虑中。&/b&
&& * @param fileName 需要修改最后访问时间的文件的文件名。
&& * @since& 0.1
& public static void touch(String fileName) {
&&& File file = new File(fileName);
&&& touch(file);
&& * 修改文件的最后访问时间。
&& * 如果文件不存在则创建该文件。
&& * &b&目前这个方法的行为方式还不稳定,主要是方法有些信息输出,这些信息输出是否保留还在考
虑中。&/b&
&& * @param files 需要修改最后访问时间的文件数组。
&& * @since& 0.1
& public static void touch(File[] files) {
&&& for (int i = 0; i & files. i++) {
&&&&& touch(files);
&& * 修改文件的最后访问时间。
&& * 如果文件不存在则创建该文件。
&& * &b&目前这个方法的行为方式还不稳定,主要是方法有些信息输出,这些信息输出是否保留还在考
虑中。&/b&
&& * @param fileNames 需要修改最后访问时间的文件名数组。
&& * @since& 0.1
& public static void touch(String[] fileNames) {
&&& File[] files = new File[fileNames.length];
&&& for (int i = 0; i & fileNames. i++) {
&&&&& files = new File(fileNames);
&&& touch(files);
&& * 判断指定的文件是否存在。
&& * @param fileName 要判断的文件的文件名
&& * @return 存在时返回true,否则返回false。
&& * @since& 0.1
& public static boolean isFileExist(String fileName) {
&&& return new File(fileName).isFile();
&& * 创建指定的目录。
&& * 如果指定的目录的父目录不存在则创建其目录书上所有需要的父目录。
&& * &b&注意:可能会在返回false的时候创建部分父目录。&/b&
&& * @param file 要创建的目录
&& * @return 完全创建成功时返回true,否则返回false。
&& * @since& 0.1
& public static boolean makeDirectory(File file) {
&&& File parent = file.getParentFile();
&&& if (parent != null) {
&&&&& return parent.mkdirs();
&& * 创建指定的目录。
&& * 如果指定的目录的父目录不存在则创建其目录书上所有需要的父目录。
&& * &b&注意:可能会在返回false的时候创建部分父目录。&/b&
&& * @param fileName 要创建的目录的目录名
&& * @return 完全创建成功时返回true,否则返回false。
&& * @since& 0.1
& public static boolean makeDirectory(String fileName) {
&&& File file = new File(fileName);
&&& return makeDirectory(file);
&& * 清空指定目录中的文件。
&& * 这个方法将尽可能删除所有的文件,但是只要有一个文件没有被删除都会返回false。
&& * 另外这个方法不会迭代删除,即不会删除子目录及其内容。
&& * @param directory 要清空的目录
&& * @return 目录下的所有文件都被成功删除时返回true,否则返回false.
&& * @since& 0.1
& public static boolean emptyDirectory(File directory) {
&&& boolean result =
&&& File[] entries = directory.listFiles();
&&& for (int i = 0; i & entries. i++) {
&&&&& if (!entries.delete()) {
&&&&&&& result =
&& * 清空指定目录中的文件。
&& * 这个方法将尽可能删除所有的文件,但是只要有一个文件没有被删除都会返回false。
&& * 另外这个方法不会迭代删除,即不会删除子目录及其内容。
&& * @param directoryName 要清空的目录的目录名
&& * @return 目录下的所有文件都被成功删除时返回true,否则返回false。
&& * @since& 0.1
& public static boolean emptyDirectory(String directoryName) {
&&& File dir = new File(directoryName);
&&& return emptyDirectory(dir);
&& * 删除指定目录及其中的所有内容。
&& * @param dirName 要删除的目录的目录名
&& * @return 删除成功时返回true,否则返回false。
&& * @since& 0.1
& public static boolean deleteDirectory(String dirName) {
&&& return deleteDirectory(new File(dirName));
&& * 删除指定目录及其中的所有内容。
&& * @param dir 要删除的目录
&& * @return 删除成功时返回true,否则返回false。
&& * @since& 0.1
& public static boolean deleteDirectory(File dir) {
&&& if ( (dir == null) || !dir.isDirectory()) {
&&&&& throw new IllegalArgumentException(&Argument & + dir +
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& & is not a directory. &);
&&& File[] entries = dir.listFiles();
&&& int sz = entries.
&&& for (int i = 0; i & i++) {
&&&&& if (entries.isDirectory()) {
&&&&&&& if (!deleteDirectory(entries)) {
&&&&& else {
&&&&&&& if (!entries.delete()) {
&&& if (!dir.delete()) {
&& * 返回文件的URL地址。
&& * @param file 文件
&& * @return 文件对应的的URL地址
&& * @throws MalformedURLException
&& * @since& 0.4
&& * @deprecated 在实现的时候没有注意到File类本身带一个toURL方法将文件路径转换为URL。
&& *&&&&&&&&&&&& 请使用File.toURL方法。
& public static URL getURL(File file) throws MalformedURLException {
&&& String fileURL = &file:/& + file.getAbsolutePath();
&&& URL url = new URL(fileURL);
&& * 从文件路径得到文件名。
&& * @param filePath 文件的路径,可以是相对路径也可以是绝对路径
&& * @return 对应的文件名
&& * @since& 0.4
& public static String getFileName(String filePath) {
&&& File file = new File(filePath);
&&& return file.getName();
&& * 从文件名得到文件绝对路径。
&& * @param fileName 文件名
&& * @return 对应的文件路径
&& * @since& 0.4
& public static String getFilePath(String fileName) {
&&& File file = new File(fileName);
&&& return file.getAbsolutePath();
&& * 将DOS/Windows格式的路径转换为UNIX/Linux格式的路径。
&& * 其实就是将路径中的&\&全部换为&/&,因为在某些情况下我们转换为这种方式比较方便,
&& * 某中程度上说&/&比&\&更适合作为路径分隔符,而且DOS/Windows也将它当作路径分隔符。
&& * @param filePath 转换前的路径
&& * @return 转换后的路径
&& * @since& 0.4
& public static String toUNIXpath(String filePath) {
&&& return filePath.replace('\\', '/');
&& * 从文件名得到UNIX风格的文件绝对路径。
&& * @param fileName 文件名
&& * @return 对应的UNIX风格的文件路径
&& * @since& 0.4
&& * @see #toUNIXpath(String filePath) toUNIXpath
& public static String getUNIXfilePath(String fileName) {
&&& File file = new File(fileName);
&&& return toUNIXpath(file.getAbsolutePath());
&& * 得到文件的类型。
&& * 实际上就是得到文件名中最后一个“.”后面的部分。
&& * @param fileName 文件名
&& * @return 文件名中的类型部分
&& * @since& 0.5
& public static String getTypePart(String fileName) {
&&& int point = fileName.lastIndexOf('.');
&&& int length = fileName.length();
&&& if (point == -1 || point == length - 1) {
&&&&& return &&;
&&& else {
&&&&& return fileName.substring(point + 1, length);
&& * 得到文件的类型。
&& * 实际上就是得到文件名中最后一个“.”后面的部分。
&& * @param file 文件
&& * @return 文件名中的类型部分
&& * @since& 0.5
& public static String getFileType(File file) {
&&& return getTypePart(file.getName());
&& * 得到文件的名字部分。
&& * 实际上就是路径中的最后一个路径分隔符后的部分。
&& * @param fileName 文件名
&& * @return 文件名中的名字部分
&& * @since& 0.5
& public static String getNamePart(String fileName) {
&&& int point = getPathLsatIndex(fileName);
&&& int length = fileName.length();
&&& if (point == -1) {
&&&&& return fileN
&&& else if (point == length - 1) {
&&&&& int secondPoint = getPathLsatIndex(fileName, point - 1);
&&&&& if (secondPoint == -1) {
&&&&&&& if (length == 1) {
&&&&&&&&& return fileN
&&&&&&& else {
&&&&&&&&& return fileName.substring(0, point);
&&&&& else {
&&&&&&& return fileName.substring(secondPoint + 1, point);
&&& else {
&&&&& return fileName.substring(point + 1);
&& * 得到文件名中的父路径部分。
&& * 对两种路径分隔符都有效。
&& * 不存在时返回&&。
&& * 如果文件名是以路径分隔符结尾的则不考虑该分隔符,例如&/path/&返回&&。
&& * @param fileName 文件名
&& * @return 父路径,不存在或者已经是父目录时返回&&
&& * @since& 0.5
& public static String getPathPart(String fileName) {
&&& int point = getPathLsatIndex(fileName);
&&& int length = fileName.length();
&&& if (point == -1) {
&&&&& return &&;
&&& else if (point == length - 1) {
&&&&& int secondPoint = getPathLsatIndex(fileName, point - 1);
&&&&& if (secondPoint == -1) {
&&&&&&& return &&;
&&&&& else {
&&&&&&& return fileName.substring(0, secondPoint);
&&& else {
&&&&& return fileName.substring(0, point);
&& * 得到路径分隔符在文件路径中首次出现的位置。
&& * 对于DOS或者UNIX风格的分隔符都可以。
&& * @param fileName 文件路径
&& * @return 路径分隔符在路径中首次出现的位置,没有出现时返回-1。
&& * @since& 0.5
& public static int getPathIndex(String fileName) {
&&& int point = fileName.indexOf('/');
&&& if (point == -1) {
&&&&& point = fileName.indexOf('\\');
&& * 得到路径分隔符在文件路径中指定位置后首次出现的位置。
&& * 对于DOS或者UNIX风格的分隔符都可以。
&& * @param fileName 文件路径
&& * @param fromIndex 开始查找的位置
&& * @return 路径分隔符在路径中指定位置后首次出现的位置,没有出现时返回-1。
&& * @since& 0.5
& public static int getPathIndex(String fileName, int fromIndex) {
&&& int point = fileName.indexOf('/', fromIndex);
&&& if (point == -1) {
&&&&& point = fileName.indexOf('\\', fromIndex);
&& * 得到路径分隔符在文件路径中最后出现的位置。
&& * 对于DOS或者UNIX风格的分隔符都可以。
&& * @param fileName 文件路径
&& * @return 路径分隔符在路径中最后出现的位置,没有出现时返回-1。
&& * @since& 0.5
& public static int getPathLsatIndex(String fileName) {
&&& int point = fileName.lastIndexOf('/');
&&& if (point == -1) {
&&&&& point = fileName.lastIndexOf('\\');
&& * 得到路径分隔符在文件路径中指定位置前最后出现的位置。
&& * 对于DOS或者UNIX风格的分隔符都可以。
&& * @param fileName 文件路径
&& * @param fromIndex 开始查找的位置
&& * @return 路径分隔符在路径中指定位置前最后出现的位置,没有出现时返回-1。
&& * @since& 0.5
& public static int getPathLsatIndex(String fileName, int fromIndex) {
&&& int point = fileName.lastIndexOf('/', fromIndex);
&&& if (point == -1) {
&&&&& point = fileName.lastIndexOf('\\', fromIndex);
&& * 将文件名中的类型部分去掉。
&& * @param filename 文件名
&& * @return 去掉类型部分的结果
&& * @since& 0.5
& public static String trimType(String filename) {
&&& int index = filename.lastIndexOf(&.&);
&&& if (index != -1) {
&&&&& return filename.substring(0, index);
&&& else {
&& * 得到相对路径。
&& * 文件名不是目录名的子节点时返回文件名。
&& * @param pathName 目录名
&& * @param fileName 文件名
&& * @return 得到文件名相对于目录名的相对路径,目录下不存在该文件时返回文件名
&& * @since& 0.5
& public static String getSubpath(String pathName,String fileName) {
&&& int index = fileName.indexOf(pathName);
&&& if (index != -1) {
&&&&& return fileName.substring(index + pathName.length() + 1);
&&& else {
&&&&& return fileN
&4.遗留问题
目前new FileInputStream()只会使用绝对路径,相对没用过,因为要相对于web服务器地址,比较麻烦
还不如写个配置文件来的快哪
5.按Java文件类型分类读取配置文件
配置文件是应用系统中不可缺少的,可以增加程序的灵活性。java.util.Properties是从jdk1.2就有的类,一直到现在都支持load ()方法,jdk1.4以后save(output,string) -&store(output,string)。如果只是单纯的读,根本不存在烦恼的问题。web层可以通过 Thread.currentThread().getContextClassLoader().
getResourceAsStream(&xx.properties&) 获取;Application可以通过new FileInputStream(&xx.properties&);直接在classes一级获取。关键是有时我们需要通过web修改配置文件,我们不能将路径写死了。经过测试觉得有以下心得:
1.servlet中读写。如果运用Struts 或者Servlet可以直接在初始化参数中配置,调用时根据servlet的getRealPath(&/&)获取真实路径,再根据String file = this.servlet.getInitParameter(&abc&);获取相对的WEB-INF的相对路径。
InputStream input = Thread.currentThread().getContextClassLoader().
getResourceAsStream(&abc.properties&);
Properties prop = new Properties();
prop.load(input);
input.close();
OutputStream out = new FileOutputStream(path);
prop.setProperty(&abc&, “test&);
prop.store(out, “–test–&);
out.close();
2.直接在jsp中操作,通过jsp内置对象获取可操作的绝对地址。
// jsp页面
String path = pageContext.getServletContext().getRealPath(&/&);
String realPath = path+&/WEB-INF/classes/abc.properties&;
//java 程序
InputStream in = getClass().getClassLoader().getResourceAsStream(&abc.properties&); // abc.properties放在webroot/WEB-INF/classes/目录下
prop.load(in);
in.close();
OutputStream out = new FileOutputStream(path); // path为通过页面传入的路径
prop.setProperty(&abc&, “abcccccc&);
prop.store(out, “–test–&);
out.close();
3.只通过Java程序操作资源文件
InputStream in = new FileInputStream(&abc.properties&); // 放在classes同级
OutputStream out = new FileOutputStream(&abc.properties&);
参考知识库
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
访问:274362次
积分:2626
积分:2626
排名:第10140名
原创:18篇
转载:105篇
评论:32条
(1)(1)(1)(9)(1)(3)(4)(11)(11)(6)(21)(22)(7)(2)(8)(1)(2)(5)(2)(3)(1)(1)(2)2336人阅读
B1_JAVA(34)
1、在Java项目中,应该通过绝对路径访问文件,以下为访问的常用方法:
第一种方法:类名.class.getResource(&/&).getPath()+文件名
第二种方法:Thread.currentThread().getContextClassLoader().getResource(&&).getPath()+文件名【主要使用】
假设目录结构如下
现在src目录下的类文件需要访问config目录下的配置文件。
2、使用第一种方法
new FileInputStream(LoadProperties.class.getResource(&/&).getPath() + &seed.txt&);new FileInputStream(MyCrawler.class.getResource(&/&).getPath() + &search.properties&)假设Jediael项目被部署在E:\Project\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\,则
类名.class.getResource(&/&) 返回file:\E:\Project\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\Jediael\WEB-INF\classes,即类文件的要目录
类名.class.getResource(&&) 返回file:\E:\Project\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\Jediael\WEB-INF\classes\com\jediael\,即类所有的位置
上述2个方法均返回URI的格式,再通过getPath()来获取路径,即将前面的file:\去掉。
3、使用第二种方法
new FileInputStream(Thread.currentThread().getContextClassLoader().getResource(&&).getPath() + &search.properties&)new FileInputStream(Thread.currentThread().getContextClassLoader().getResource(&&).getPath() + &seed.txt&);二者均返回:E:\Project\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\Jediael\WEB-INF\classes
推荐使用第二种方法!!
以下内容转载自:http://blog.csdn.net/shendl/article/details/1427475
Java的路径问题,非常难搞。最近的工作涉及到创建和读取文件的工作,这里我就给大家彻底得解决Java路径问题。
我编写了一个方法,比ClassLoader.getResource(String 相对路径)方法的能力更强。它可以接受“../”这样的参数,允许我们用相对路径来定位classpath外面的资源。这样,我们就可以使用相对于classpath的路径,定位所有位置的资源!
Java中使用的路径,分为两种:绝对路径和相对路径。具体而言,又分为四种:
一、URI形式的绝对资源路径
如:file:/D:/java/eclipse32/workspace/jbpmtest3/bin/aaa.b
URL是URI的特例。URL的前缀/协议,必须是Java认识的。URL可以打开资源,而URI则不行。
URL和URI对象可以互相转换,使用各自的toURI(),toURL()方法即可!
二、本地系统的绝对路径
D:/java/eclipse32/workspace/jbpmtest3/bin/aaa.b
Java.io包中的类,需要使用这种形式的参数。
但是,它们一般也提供了URI类型的参数,而URI类型的参数,接受的是URI样式的String。因此,通过URI转换,还是可以把URI样式的绝对路径用在java.io包中的类中。
三、相对于classpath的相对路径
如:相对于
file:/D:/java/eclipse32/workspace/jbpmtest3/bin/这个路径的相对路径。其中,bin是本项目的classpath。所有的Java源文件编译后的.class文件复制到这个目录中。
四、相对于当前用户目录的相对路径
就是相对于System.getProperty(&user.dir&)返回的路径。
对于一般项目,这是项目的根路径。对于JavaEE服务器,这可能是服务器的某个路径。这个并没有统一的规范!
所以,绝对不要使用“相对于当前用户目录的相对路径”。然而:
默认情况下,java.io 包中的类总是根据当前用户目录来分析相对路径名。此目录由系统属性 user.dir 指定,通常是 Java 虚拟机的调用目录。
这就是说,在使用java.io包中的类时,最好不要使用相对路径。否则,虽然在J2SE应用程序中可能还算正常,但是到了J2EE程序中,一定会出问题!而且这个路径,在不同的服务器中都是不同的!
相对路径最佳实践
推荐使用相对于当前classpath的相对路径
因此,我们在使用相对路径时,应当使用相对于当前classpath的相对路径。
ClassLoader类的getResource(String name),getResourceAsStream(String name)等方法,使用相对于当前项目的classpath的相对路径来查找资源。
读取属性文件常用到的ResourceBundle类的getBundle(String path)也是如此。
通过查看ClassLoader类及其相关类的源代码,我发现,它实际上还是使用了URI形式的绝对路径。通过得到当前classpath的URI形式的绝对路径,构建了相对路径的URI形式的绝对路径。(这个实际上是猜想,因为JDK内部调用了SUN的源代码,而这些代码不属于JDK,不是开源的。)
相对路径本质上还是绝对路径
因此,归根结底,Java本质上只能使用绝对路径来寻找资源。所有的相对路径寻找资源的方法,都不过是一些便利方法。不过是API在底层帮助我们构建了绝对路径,从而找到资源的!
得到classpath和当前类的绝对路径的一些方法
&&&&下面是一些得到classpath和当前类的绝对路径的一些方法。你可能需要使用其中的一些方法来得到你需要的资源的绝对路径。
1,FileTest.class.getResource(&&)
得到的是当前类FileTest.class文件的URI目录。不包括自己!
如:file:/D:/java/eclipse32/workspace/jbpmtest3/bin/com/test/
2,FileTest.class.getResource(&/&)
得到的是当前的classpath的绝对URI路径。
如:file:/D:/java/eclipse32/workspace/jbpmtest3/bin/
3,Thread.currentThread().getContextClassLoader().getResource(&&)
得到的也是当前ClassPath的绝对URI路径。
如:file:/D:/java/eclipse32/workspace/jbpmtest3/bin/
4,FileTest.class.getClassLoader().getResource(&&)
得到的也是当前ClassPath的绝对URI路径。
如:file:/D:/java/eclipse32/workspace/jbpmtest3/bin/
5,ClassLoader.getSystemResource(&&)
得到的也是当前ClassPath的绝对URI路径。
如:file:/D:/java/eclipse32/workspace/jbpmtest3/bin/
我推荐使用Thread.currentThread().getContextClassLoader().getResource(&&)来得到当前的classpath的绝对路径的URI表示法。
Web应用程序中资源的寻址
&&&&上文中说过,当前用户目录,即相对于System.getProperty(&user.dir&)返回的路径。
对于JavaEE服务器,这可能是服务器的某个路径,这个并没有统一的规范!
而不是我们发布的Web应用程序的根目录!
这样,在Web应用程序中,我们绝对不能使用相对于当前用户目录的相对路径。
在Web应用程序中,我们一般通过ServletContext.getRealPath(&/&)方法得到Web应用程序的根目录的绝对路径。
这样,我们只需要提供相对于Web应用程序根目录的路径,就可以构建出定位资源的绝对路径。
这是我们开发Web应用程序时一般所采取的策略。
通用的相对路径解决办法
Java中各种相对路径非常多,不容易使用,非常容易出错。因此,我编写了一个便利方法,帮助更容易的解决相对路径问题。
Web应用程序中使用JavaSE运行的资源寻址问题
在JavaSE程序中,我们一般使用classpath来作为存放资源的目的地。但是,在Web应用程序中,我们一般使用classpath外面的WEB-INF及其子目录作为资源文件的存放地。
在Web应用程序中,我们一般通过ServletContext.getRealPath(&/&)方法得到Web应用程序的根目录的绝对路径。这样,我们只需要提供相对于Web应用程序根目录的路径,就可以构建出定位资源的绝对路径。
Web应用程序,可以作为Web应用程序进行发布和运行。但是,我们也常常会以JavaSE的方式来运行Web应用程序的某个类的main方法。或者,使用JUnit测试。这都需要使用JavaSE的方式来运行。
这样,我们就无法使用ServletContext.getRealPath(&/&)方法得到Web应用程序的根目录的绝对路径。
而JDK提供的ClassLoader类,
它的getResource(String name),getResourceAsStream(String name)等方法,使用相对于当前项目的classpath的相对路径来查找资源。
读取属性文件常用到的ResourceBundle类的getBundle(String path)也是如此。
它们都只能使用相对路径来读取classpath下的资源,无法定位到classpath外面的资源。
Classpath外配置文件读取问题
如,我们使用测试驱动开发的方法,开发Spring、Hibernate、iBatis等使用配置文件的Web应用程序,就会遇到问题。
尽管Spring自己提供了FileSystem(也就是相对于user,dir目录)来读取Web配置文件的方法,但是终究不是很方便。而且与Web程序中的代码使用方式不一致!
至于Hibernate,iBatis就更麻烦了!只有把配置文件移到classpath下,否则根本不可能使用测试驱动开发!
&&&&这怎么办?
通用的相对路径解决办法
面对这个问题,我决定编写一个助手类ClassLoaderUtil,提供一个便利方法[public&static&URL getExtendResource(String relativePath)]。在Web应用程序等一切Java程序中,需要定位classpath外的资源时,都使用这个助手类的便利方法,而不使用Web应用程序特有的ServletContext.getRealPath(&/&)方法来定位资源。
利用classpath的绝对路径,定位所有资源
这个便利方法的实现原理,就是“利用classpath的绝对路径,定位所有资源”。
ClassLoader类的getResource(&&)方法能够得到当前classpath的绝对路径,这是所有Java程序都拥有的能力,具有最大的适应性!
而目前的JDK提供的ClassLoader类的getResource(String 相对路径)方法,只能接受一般的相对路径。这样,使用ClassLoader类的getResource(String 相对路径)方法就只能定位到classpath下的资源。
如果,它能够接受“../”这样的参数,允许我们用相对路径来定位classpath外面的资源,那么我们就可以定位位置的资源!
当然,我无法修改ClassLoader类的这个方法,于是,我编写了一个助手类ClassLoaderUtil类,提供了[public&static&URL getExtendResource(String relativePath)]这个方法。它能够接受带有“../”符号的相对路径,实现了自由寻找资源的功能。
通过相对classpath路径实现自由寻找资源的助手类的源代码:
import&java.io.IOE
import&java.io.InputS
import&java.net.MalformedURLE
import&java.net.URL;
import&java.util.P
import&mons.logging.L
import&mons.logging.LogF
&*@author沈东良shendl_
&*Nov29,2006&10:34:34AM
&*用来加载类,classpath下的资源文件,属性文件等。
&*getExtendResource(StringrelativePath)方法,可以使用../符号来加载classpath外部的资源。
publicclass&ClassLoaderUtil
&&&&privatestatic&Log&log=LogFactory.getLog(ClassLoaderUtil.class);
&&& &*Thread.currentThread().getContextClassLoader().getResource(&&)
&&& &*加载Java类。&使用全限定类名
&&& &*@paramclassName
&&& &*@return
&&&&publicstatic&Class
loadClass(String className) {
&&& &&&&try&{
&&& &&&&&&return&getClassLoader().loadClass(className);
&&& &&& }&catch&(ClassNotFoundException
&&& &&&&&&thrownew&RuntimeException(&class
not found '&+className+&'&, e);
&&& &&&*得到类加载器
&&& &&&*@return
&&& &publicstatic&ClassLoader
getClassLoader() {
&&& &&&&return&ClassLoaderUtil.class.getClassLoader();
&&& &&&*提供相对于classpath的资源路径,返回文件的输入流
&&& &&&*@paramrelativePath必须传递资源的相对路径。是相对于classpath的路径。如果需要查找classpath外部的资源,需要使用../来查找
&&& &&&*@return&文件输入流
&&& &*@throwsIOException
&&& &*@throwsMalformedURLException
&&& &publicstatic&InputStream
getStream(String relativePath)&throws&MalformedURLException, IOException {
&&&&&&& &if(!relativePath.contains(&../&)){
&&&&&&&&&&& &return&getClassLoader().getResourceAsStream(relativePath);
&&&&&&&&&&& &
&&&&&&& &}else{
&&&&&&&&&&& &return&ClassLoaderUtil.getStreamByExtendResource(relativePath);
&&&&&&& &}
&&& &&&*@paramurl
&&& &&&*@return
&&& &&&*@throwsIOException
&&& &publicstatic&InputStream
getStream(URL url)&throws&IOException{
&&&&&&& &if(url!=null){
&&&&&&&&&&& &
&&&&&&&&&&&&&&&&return&url.openStream();
&&&&&&&&&&&
&&&&&&&&&&& &
&&&&&&& &}else{
&&&&&&&&&&& &returnnull;
&&&&&&& &}
&&& &&&*@paramrelativePath必须传递资源的相对路径。是相对于classpath的路径。如果需要查找classpath外部的资源,需要使用../来查找
&&& &&&*@return
&&& &&&*@throwsMalformedURLException
&&& &&&*@throwsIOException
&&& &publicstatic&InputStream
getStreamByExtendResource(String relativePath)&throws&MalformedURLException, IOException{
&&&&&&&&return&ClassLoaderUtil.getStream(ClassLoaderUtil.getExtendResource(relativePath));
&&&&&&&*提供相对于classpath的资源路径,返回属性对象,它是一个散列表
&&&&&&&*@paramresource
&&&&&&&*@return
&&& &publicstatic&Properties
getProperties(String resource) {
&&& &&& Properties properties =&new&Properties();
&&& &&&&try&{
&&& &&&&& properties.load(getStream(resource));
&&& &&& }&catch&(IOException e) {
&&& &&&&&&thrownew&RuntimeException(&couldn't
load properties file '&+resource+&'&, e);
&&& &&&&return&
&&& &&&*得到本Class所在的ClassLoader的Classpat的绝对路径。
&&& &&&*URL形式的
&&& &&&*@return
&&& &publicstatic&String
getAbsolutePathOfClassLoaderClassPath(){
&&&&&&& &ClassLoaderUtil.log.info(ClassLoaderUtil.getClassLoader().getResource(&&).toString());
&&&&&&& &return&ClassLoaderUtil.getClassLoader().getResource(&&).toString();
&&& &&&*@paramrelativePath&必须传递资源的相对路径。是相对于classpath的路径。如果需要查找classpath外部的资源,需要使用../来查找
&&& &&&*@return资源的绝对URL
&&& &*@throwsMalformedURLException
&&& &publicstatic&URL
getExtendResource(String relativePath)&throws&MalformedURLException{
&&&&&&& &ClassLoaderUtil.log.info(&传入的相对路径:&+relativePath)
&&&&&&& &//(Integer.valueOf(relativePath.indexOf(&../&))) ;
&&&&&&& &if(!relativePath.contains(&../&)){
&&&&&&&&&&& &return&ClassLoaderUtil.getResource(relativePath);
&&&&&&&&&&& &
&&&&&&& &}
&&&&&&& &String classPathAbsolutePath=ClassLoaderUtil.getAbsolutePathOfClassLoaderClassPath();
&&&&&&& &if(relativePath.substring(0, 1).equals(&/&)){
&&&&&&&&&&& &relativePath=relativePath.substring(1);
&&&&&&& &}
&&&&&&& &ClassLoaderUtil.log.info(Integer.valueOf(relativePath.lastIndexOf(&../&)))
&&&&&&& &String wildcardString=relativePath.substring(0,relativePath.lastIndexOf(&../&)+3);
&&&&&&& relativePath=relativePath.substring(relativePath.lastIndexOf(&../&)+3);
&&&&&&& &int&containSum=ClassLoaderUtil.containSum(wildcardString,&&../&);
&&&&&&& &classPathAbsolutePath= ClassLoaderUtil.cutLastString(classPathAbsolutePath,&&/&,
containSum);
&&&&&&& &String resourceAbsolutePath=classPathAbsolutePath+relativeP
&&&&&&& &ClassLoaderUtil.log.info(&绝对路径:&+resourceAbsolutePath)
&&&&&&& &URL resourceAbsoluteURL=new&URL(resourceAbsolutePath);
&&&&&&& &return&resourceAbsoluteURL;
&&& &&&*@paramsource
&&& &&&*@paramdest
&&& &&&*@return
&&& &privatestaticint&containSum(String
source,String dest){
&&&&&&& &int&containSum=0;
&&&&&&& &int&destLength=dest.length();
&&&&&&& &while(source.contains(dest)){
&&&&&&&&&&& &containSum=containSum+1;
&&&&&&&&&&& &source=source.substring(destLength);
&&&&&&&&&&& &
&&&&&&& &}
&&&&&&& &return&containS
&&& &&&*@paramsource
&&& &&&*@paramdest
&&& &&&*@paramnum
&&& &&&*@return
&&& &privatestatic&String
cutLastString(String source,String dest,int&num){
&&&&&&& &// String cutSource=
&&&&&&& &for(int&i=0;i&i++){
&&&&&&&&&&& &source=source.substring(0, source.lastIndexOf(dest, source.length()-2)+1);
&&&&&&&&&&& &
&&&&&&&&&&& &
&&&&&&& &}
&&&&&&& &return&
&&& &&&*@paramresource
&&& &&&*@return
&&&&&&publicstatic&URL
getResource(String resource){
&&& &&ClassLoaderUtil.log.info(&传入的相对于classpath的路径:&+resource)
&&&&&&& &return&ClassLoaderUtil.getClassLoader().getResource(resource);
&&& &*@paramargs
&&& &*@throwsMalformedURLException
&&&&publicstaticvoid&main(String[]
args)&throws&MalformedURLException {
&&&&&&&&&&&&//ClassLoaderUtil.getExtendResource(&../spring/dao.xml&);
&&&&&&&&//ClassLoaderUtil.getExtendResource(&../../../src/log4j.properties&);
&&&&&&& ClassLoaderUtil.getExtendResource(&log4j.properties&);
&&&&&&& System.out.println(ClassLoaderUtil.getClassLoader().getResource(&log4j.properties&).toString());
ClassLoaderUtil类的public static URL getExtendResource(String relativePath),虽然很简单,但是确实可以解决大问题。
不过这个方法还是比较简陋的。我还想在未来有空时,进一步增强它的能力。比如,增加Ant风格的匹配符。用**代表多个目录,*代表多个字符,?代表一个字符。达到Spring那样的能力,一次返回多个资源的URL,进一步方便大家开发。
1,尽量不要使用相对于System.getProperty(&user.dir&)当前用户目录的相对路径。这是一颗定时炸弹,随时可能要你的命。
2,尽量使用URI形式的绝对路径资源。它可以很容易的转变为URI,URL,File对象。
3,尽量使用相对classpath的相对路径。不要使用绝对路径。使用上面ClassLoaderUtil类的public static URL getExtendResource(String relativePath)方法已经能够使用相对于classpath的相对路径定位所有位置的资源。
4,绝对不要使用硬编码的绝对路径。因为,我们完全可以使用ClassLoader类的getResource(&&)方法得到当前classpath的绝对路径。
使用硬编码的绝对路径是完全没有必要的!它一定会让你死的很难看!程序将无法移植!
如果你一定要指定一个绝对路径,那么使用配置文件,也比硬编码要好得多!
当然,我还是推荐你使用程序得到classpath的绝对路径来拼资源的绝对路径!
参考知识库
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
访问:927698次
积分:9917
积分:9917
排名:第1195名
原创:194篇
转载:77篇
评论:92条
(1)(3)(1)(10)(16)(16)(11)(3)(21)(27)(26)(23)(6)(2)(17)(21)(7)(6)(3)(5)(2)(36)(1)(1)(6)

我要回帖

更多关于 swing 绝对布局 的文章

 

随机推荐