Java文件获取路径方式:
转自:http://blog.csdn.net/appleprince88/article/details/11599805# 谢谢!
由于经常需要获取文件的路径,但是比较容易忘记,每次需要总需要查询,现在把这些方式写下来,方便自己的时候也方便大家了,如果大家在下面的方法遇到什么问题,可以留言。
各种获取方式如示例代码所示:
- package first.second;
- import java.io.File;
- public class GetPath {
- public static void getPath()
- {
- //方式一
- System.out.println(System.getProperty("user.dir"));
- //方式二
- File directory = new File("");//设定为当前文件夹
- try{
- System.out.println(directory.getCanonicalPath());//获取标准的路径
- System.out.println(directory.getAbsolutePath());//获取绝对路径
- }catch(Exception e)
- {
- e.printStackTrace();
- }
- //方式三
- System.out.println(GetPath.class.getResource("/"));
- System.out.println(GetPath.class.getResource(""));
- //方式4
- System.out.println(GetPath.class.getClassLoader().getResource(""));
- System.out.println(GetPath.class.getClassLoader().getResource("source.xml"));
- }
- /**
- * @param args
- */
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- GetPath.getPath();
- }
- }
其在java project项目下输出如下:
- 方式一
- D:\eclipse\juno_workspace\Test
- 方式二
- D:\eclipse\juno_workspace\Test
- D:\eclipse\juno_workspace\Test
- 方式三
- file:/D:/eclipse/juno_workspace/Test/bin/
- file:/D:/eclipse/juno_workspace/Test/bin/first/second/
- 方式四
- file:/D:/eclipse/juno_workspace/Test/bin/
- file:/D:/eclipse/juno_workspace/Test/bin/source.xml
在Web project输出如下:
- 方式一
- D:\apache-tomcat-6.0.36\bin
- 方式二
- D:\apache-tomcat-6.0.36\bin
- D:\apache-tomcat-6.0.36\bin
- 方式三
- file:/D:/apache-tomcat-6.0.36/webapps/ConsisPro/WEB-INF/classes/
- file:/D:/apache-tomcat-6.0.36/webapps/ConsisPro/WEB-INF/classes/first/second/
- 方式四
- file:/D:/apache-tomcat-6.0.36/webapps/ConsisPro/WEB-INF/classes/
- file:/D:/apache-tomcat-6.0.36/webapps/ConsisPro/WEB-INF/classes/source.xml
说明一下,实验类是放在first.second包下的,source.xml是src文件下的一个文件。在java project测试的项目名是Test,在web project测试的项目名是ConsisPro,还有就是 web project项目测试时运行在tomcat中,通过调用实验类GetPath产生的运行结果。
从上面我们可以看出方式一和方式二在java project项目下是获取的项目根目录,而在web project项目下获取的是tomcat的bin目录。
方式三当使用“/”时获取的是类编译后所在的目录,当不使用“/”是获取的是编译好类所在的目录,也就是前面加“/”产生的目录加上相应的包目录。
方式四中第一个获取的也是类编译后的目录,第二个获取的是也就是我们放在src目录底下的文件,编译后放在类编译后的目录底下,当我们需要获取放在Src目录底下的文件时,用这个方式很方便。
二.获取文件的一些具体情况下的方式
1.获取你存放在src目录下的文件,一般为配置文件,如下图1所示。推荐使用方式四的中的第二个方式,示例代码如下:
图1
- /* @param name 文件名 不包含路径
- */
- public static String getSrcPath(String name)
- {
- String result=null;
- URL urlpath = GetPath.class.getClassLoader().getResource(name);
- String path=urlpath.toString();
- //remove the head "file:",if it exists
- if(path.startsWith("file"))
- {
- path=path.substring(5);
- }
- path.replace("/", File.separator);
- result=path;
- return result;
- }
2.在java project获取与src文件夹并列的文件下的文件,如下图2所示。这种情况推荐使用方式一和方式二,下面以第一种方式给出示例代码:
图2
- // filename 文件名 不包含路径
- // ...args 文件夹名 可以输入多个文件夹名参数
- public static String getParallelPath(String filename,String ...args)
- {
- String pre=System.getProperty("user.dir");
- String path=pre;
- for(String arg:args)
- {
- path+=File.separator+arg;
- }
- path+=File.separator+filename;
- if(path.startsWith("file"))
- {
- path=path.substring(5);
- }
- path.replace("/", File.separator);
- return path;
- }
3.如果希望无论在java project或者web project项目使用类包底下的一些文件,如下图3所示。这种情况可以使用方式三中的第二种方式,使用示例代码如下:
图3
- public static String getPackagePath(String filename)
- {
- String result=null;
- URL urlpath=GetPath.class.getResource("");
- String path=urlpath.toString();
- if(path.startsWith("file"))
- {
- path=path.substring(5);
- }
- path.replace("/", File.separator);
- result=path+filename;
- return result;
- }
Tips:这个方法要在和要获取的文件在同一个包中才可以,在不同包中,需要使用其它方式
4.当在web project项目下想获取WebRoot目录底下自定义目录文件下的文件,如下图4所示。这种情况推荐方式三和方式四,进行一些操作,下面是一个示例代码:
图4
- //获取WebRoot目录
- public static String getWebRootPath()
- {
- URL urlpath=GetPath.class.getResource("");
- String path=urlpath.toString();
- if(path.startsWith("file"))
- {
- path=path.substring(5);
- }
- if(path.indexOf("WEB-INF")>0)
- {
- path=path.substring(0,path.indexOf("WEB-INF")-1);
- }
- path.replace("/", File.separator);
- return path;
- }
- //webroot WebRoot目录
- //filename 文件名
- //...args 文件名所在文件夹,多个参数输入
- public static String getWebRootFilepath(String webroot,String filename,String ...args)
- {
- String pre=webroot;
- String path=pre;
- for(String arg:args)
- {
- path+=File.separator+arg;
- }
- path+=File.separator+filename;
- if(path.startsWith("file"))
- {
- path=path.substring(5);
- }
- path.replace("/", File.separator);
- return path;
- }
三.空格问题
可以用replaceAll("%20"," "); 来解决部分问题,遇到其它问题可以参考下面的文章http://www.2cto.com/kf/201108/100533.html。我认为当你得项目设为UTF-8的格式应该不会遇到空格问题。
参考文献
1. JAVA中获取路径的各种方式。http://gjt1244.blog.163.com/blog/static/19165205620118724046617/
2. Java获取当前文件路径。http://www.cnblogs.com/lostyue/archive/2011/06/27/2091686.html
3. JAVA彻底解决获取空格路径问题。http://www.2cto.com/kf/201108/100533.html
附录源代码
- package first.second;
- import java.io.BufferedReader;
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.FileNotFoundException;
- import java.io.IOException;
- import java.io.InputStreamReader;
- import java.net.URL;
- public class GetPath {
- public static void getPath()
- {
- //方式一
- System.out.println("方式一");
- System.out.println(System.getProperty("user.dir"));
- //方式二
- System.out.println("方式二");
- File directory = new File("");//设定为当前文件夹
- try{
- System.out.println(directory.getCanonicalPath());//获取标准的路径
- System.out.println(directory.getAbsolutePath());//获取绝对路径
- }catch(Exception e)
- {
- e.printStackTrace();
- }
- //方式三
- System.out.println("方式三");
- System.out.println(GetPath.class.getResource("/"));
- System.out.println(GetPath.class.getResource(""));
- //方式4
- System.out.println("方式四");
- System.out.println(GetPath.class.getClassLoader().getResource(""));
- System.out.println(GetPath.class.getClassLoader().getResource("source.xml"));
- }
- /**
- * @param name 文件名 不包含路径
- */
- public static String getSrcPath(String name)
- {
- String result=null;
- URL urlpath = GetPath.class.getClassLoader().getResource(name);
- String path=urlpath.toString();
- //remove the head "file:",if it exists
- if(path.startsWith("file"))
- {
- path=path.substring(5);
- }
- path.replace("/", File.separator);
- result=path;
- return result;
- }
- // filename 文件名 不包含路径
- // ...args 文件夹名 可以输入多个文件夹名参数
- public static String getParallelPath(String filename,String ...args)
- {
- String pre=System.getProperty("user.dir");
- String path=pre;
- for(String arg:args)
- {
- path+=File.separator+arg;
- }
- path+=File.separator+filename;
- if(path.startsWith("file"))
- {
- path=path.substring(5);
- }
- path.replace("/", File.separator);
- return path;
- }
- public static void readFile(String filepath)
- {
- File file=new File(filepath);
- try {
- InputStreamReader sr=new InputStreamReader(new FileInputStream(file));
- BufferedReader br=new BufferedReader(sr);
- String line=null;
- while((line=br.readLine())!=null)
- {
- System.out.println(line);
- }
- } catch (FileNotFoundException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- public static String getPackagePath(String filename)
- {
- String result=null;
- URL urlpath=GetPath.class.getResource("");
- String path=urlpath.toString();
- if(path.startsWith("file"))
- {
- path=path.substring(5);
- }
- path.replace("/", File.separator);
- result=path+filename;
- return result;
- }
- //获取WebRoot目录
- public static String getWebRootPath()
- {
- URL urlpath=GetPath.class.getResource("");
- String path=urlpath.toString();
- if(path.startsWith("file"))
- {
- path=path.substring(5);
- }
- if(path.indexOf("WEB-INF")>0)
- {
- path=path.substring(0,path.indexOf("WEB-INF")-1);
- }
- path.replace("/", File.separator);
- return path;
- }
- //webroot WebRoot目录
- //filename 文件名
- //...args 文件名所在文件夹,多个参数输入
- public static String getWebRootFilepath(String webroot,String filename,String ...args)
- {
- String pre=webroot;
- String path=pre;
- for(String arg:args)
- {
- path+=File.separator+arg;
- }
- path+=File.separator+filename;
- if(path.startsWith("file"))
- {
- path=path.substring(5);
- }
- path.replace("/", File.separator);
- return path;
- }
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- // GetPath.getPath();
- // //1 test
- // System.out.println(GetPath.getSrcPath("source.xml"));
- // GetPath.readFile(GetPath.getSrcPath("source.xml"));
- // //2 test
- System.out.println(GetPath.getParallelPath("source.xml", "my file"));
- GetPath.readFile(GetPath.getParallelPath("source.xml", "my file"));
- // //3 test
- System.out.println(GetPath.getPackagePath("source.xml"));
- GetPath.readFile(GetPath.getPackagePath("source.xml"));
- }
- }
Java文件获取路径方式:的更多相关文章
- JAVA中获取路径
内容来自于snannan_268 关键字: java中获取路径 JAVA中获取路径: 1.jsp中取得路径: 以工程名为TEST为例: (1)得到包含工程名的当前页面全路径:request.get ...
- java项目获取路径的几种方式
第一种: File f = new File(this.getClass().getResource("/").getPath()); System.out.println(f); ...
- 浅谈JS中的!=、== 、!==、===的用法和区别 JS中Null与Undefined的区别 读取XML文件 获取路径的方式 C#中Cookie,Session,Application的用法与区别? c#反射 抽象工厂
浅谈JS中的!=.== .!==.===的用法和区别 var num = 1; var str = '1'; var test = 1; test == num //tr ...
- java中获取路径的几种基本的方法
package com.ygh.blog.realpath; import java.io.File; import java.io.IOException; import java.io.Input ...
- Java中获取路径的各种方法
1. java文件中获得路径 Thread.currentThread().getContextClassLoader().getResource("") //获得资源文件(.cl ...
- java中获取路径中的空格处理(%20)问题
在java中获取文件路径的时候,有时候会获取到空格,但是在中文编码环境下,空格会变成“%20”从而使得路径错误. 解决办法: String path = Parameter.class.getReso ...
- java 获取路径与各文件目录的…
java 获取路径 博客分类: MyJava JavaJSPWebTomcat编程 转至:http://geeksun.iteye.com/blog/356339 (1).request.getRe ...
- Java中获取路径的方法_自我分析
就目前的我来说最常用的两种获取路径的方法是 class.getRecource(filename) 和 class.getclassloader.getRecource(filename) 这两者的 ...
- java中获取路径的方法
在class获取路径的方法,getResource有没有“\”的区别 System.out.println("" + this.getClass().getResource(&qu ...
随机推荐
- linux mono环境
安装好 CentOS 6.5 之后 1.更新系统 在命令行下执行 yum –y update 2.安装必要的软件 yum -y install gcc gcc-c++ bison pkgconfig ...
- 百度地图API示例之设置地图最大、最小级别
代码 <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" cont ...
- DescriptionResourcePathLocationType Dynamic Web Module 3.0 requires Java
先保证ide的所有jdk都在1.6及以上,如果还是错就试试下面的 在<build></build>中添加 <plugins> <plugin> < ...
- 利用 Gulp 处理前端工作流程
最近做项目,因为每次做完后都要手动压缩CSS.JS 等文件,压缩后另存为 *.min.xxx. Less 还要手动输入命令进行编译,调整页面也经常要手动刷新页面看效果,很麻烦,就尝试用 gulp 去处 ...
- Linux搭建smtp服务器+laravel5.2发邮件配置
/** * 这里主要是想通过自己搭建smtp服务器,配置laravel5.2框架,实现邮箱发邮件功能, * 主要内容是搭建smtp服务器,laravel5.2发邮件顺手提一下 */ /** * 1.l ...
- HDU 5410 CRB and His Birthday(完全背包变形)
CRB and His Birthday Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Oth ...
- HTML 透明、阴影,圆角等知识点
table两个属性:cellpadding:内容与单元格边框的距离,内部距离cellspacing:单元格之间的距离,外部距离 table合并边框线: border-collapse: co ...
- ibatis XML标签的含义
selectKey: 有3个主要的属性: 1)resultClass:返回的主键的数据类型,跟sqlMap中的数据类型一致: 2)type:表示主键在insert之前或之后生成(取决于 ...
- 错误:创建 cachingConfiguration 的配置节处理程序时出错: 未能加载文件或程序集“Microsoft.Practices.EnterpriseLibrary.Caching,
问题: 错误:创建 cachingConfiguration 的配置节处理程序时出错: 未能加载文件或程序集“Microsoft.Practices.EnterpriseLibrary.Caching ...
- iOS 判断电话号 几种方法
1.方法一 - (BOOL)isMobileNumber:(NSString *)mobileNum { /** * 手机号码 * 移动:134[0-8],135,136,137,138,139,15 ...