转自:http://blog.csdn.net/appleprince88/article/details/11599805# 谢谢!

由于经常需要获取文件的路径,但是比较容易忘记,每次需要总需要查询,现在把这些方式写下来,方便自己的时候也方便大家了,如果大家在下面的方法遇到什么问题,可以留言。

各种获取方式如示例代码所示:

  1. package first.second;
  2. import java.io.File;
  3. public class GetPath {
  4. public static void getPath()
  5. {
  6. //方式一
  7. System.out.println(System.getProperty("user.dir"));
  8. //方式二
  9. File directory = new File("");//设定为当前文件夹
  10. try{
  11. System.out.println(directory.getCanonicalPath());//获取标准的路径
  12. System.out.println(directory.getAbsolutePath());//获取绝对路径
  13. }catch(Exception e)
  14. {
  15. e.printStackTrace();
  16. }
  17. //方式三
  18. System.out.println(GetPath.class.getResource("/"));
  19. System.out.println(GetPath.class.getResource(""));
  20. //方式4
  21. System.out.println(GetPath.class.getClassLoader().getResource(""));
  22. System.out.println(GetPath.class.getClassLoader().getResource("source.xml"));
  23. }
  24. /**
  25. * @param args
  26. */
  27. public static void main(String[] args) {
  28. // TODO Auto-generated method stub
  29. GetPath.getPath();
  30. }
  31. }

其在java project项目下输出如下:

  1. 方式一
  2. D:\eclipse\juno_workspace\Test
  3. 方式二
  4. D:\eclipse\juno_workspace\Test
  5. D:\eclipse\juno_workspace\Test
  6. 方式三
  7. file:/D:/eclipse/juno_workspace/Test/bin/
  8. file:/D:/eclipse/juno_workspace/Test/bin/first/second/
  9. 方式四
  10. file:/D:/eclipse/juno_workspace/Test/bin/
  11. file:/D:/eclipse/juno_workspace/Test/bin/source.xml

在Web project输出如下:

  1. 方式一
  2. D:\apache-tomcat-6.0.36\bin
  3. 方式二
  4. D:\apache-tomcat-6.0.36\bin
  5. D:\apache-tomcat-6.0.36\bin
  6. 方式三
  7. file:/D:/apache-tomcat-6.0.36/webapps/ConsisPro/WEB-INF/classes/
  8. file:/D:/apache-tomcat-6.0.36/webapps/ConsisPro/WEB-INF/classes/first/second/
  9. 方式四
  10. file:/D:/apache-tomcat-6.0.36/webapps/ConsisPro/WEB-INF/classes/
  11. 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

  1. /* @param name   文件名  不包含路径
  2. */
  3. public static  String getSrcPath(String name)
  4. {
  5. String result=null;
  6. URL urlpath = GetPath.class.getClassLoader().getResource(name);
  7. String path=urlpath.toString();
  8. //remove the head "file:",if it exists
  9. if(path.startsWith("file"))
  10. {
  11. path=path.substring(5);
  12. }
  13. path.replace("/", File.separator);
  14. result=path;
  15. return result;
  16. }

2.在java project获取与src文件夹并列的文件下的文件,如下图2所示。这种情况推荐使用方式一和方式二,下面以第一种方式给出示例代码:

图2

  1. // filename 文件名 不包含路径
  2. // ...args  文件夹名      可以输入多个文件夹名参数
  3. public static String getParallelPath(String filename,String ...args)
  4. {
  5. String pre=System.getProperty("user.dir");
  6. String path=pre;
  7. for(String arg:args)
  8. {
  9. path+=File.separator+arg;
  10. }
  11. path+=File.separator+filename;
  12. if(path.startsWith("file"))
  13. {
  14. path=path.substring(5);
  15. }
  16. path.replace("/", File.separator);
  17. return path;
  18. }

3.如果希望无论在java project或者web project项目使用类包底下的一些文件,如下图3所示。这种情况可以使用方式三中的第二种方式,使用示例代码如下:

图3

  1. public static String getPackagePath(String filename)
  2. {
  3. String result=null;
  4. URL urlpath=GetPath.class.getResource("");
  5. String path=urlpath.toString();
  6. if(path.startsWith("file"))
  7. {
  8. path=path.substring(5);
  9. }
  10. path.replace("/", File.separator);
  11. result=path+filename;
  12. return result;
  13. }

Tips:这个方法要在和要获取的文件在同一个包中才可以,在不同包中,需要使用其它方式

4.当在web project项目下想获取WebRoot目录底下自定义目录文件下的文件,如下图4所示。这种情况推荐方式三和方式四,进行一些操作,下面是一个示例代码:

图4

  1. //获取WebRoot目录
  2. public static String getWebRootPath()
  3. {
  4. URL urlpath=GetPath.class.getResource("");
  5. String path=urlpath.toString();
  6. if(path.startsWith("file"))
  7. {
  8. path=path.substring(5);
  9. }
  10. if(path.indexOf("WEB-INF")>0)
  11. {
  12. path=path.substring(0,path.indexOf("WEB-INF")-1);
  13. }
  14. path.replace("/", File.separator);
  15. return path;
  16. }
  17. //webroot  WebRoot目录
  18. //filename  文件名
  19. //...args   文件名所在文件夹,多个参数输入
  20. public static String getWebRootFilepath(String webroot,String filename,String ...args)
  21. {
  22. String pre=webroot;
  23. String path=pre;
  24. for(String arg:args)
  25. {
  26. path+=File.separator+arg;
  27. }
  28. path+=File.separator+filename;
  29. if(path.startsWith("file"))
  30. {
  31. path=path.substring(5);
  32. }
  33. path.replace("/", File.separator);
  34. return path;
  35. }

三.空格问题

可以用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

附录源代码

  1. package first.second;
  2. import java.io.BufferedReader;
  3. import java.io.File;
  4. import java.io.FileInputStream;
  5. import java.io.FileNotFoundException;
  6. import java.io.IOException;
  7. import java.io.InputStreamReader;
  8. import java.net.URL;
  9. public class GetPath {
  10. public static void getPath()
  11. {
  12. //方式一
  13. System.out.println("方式一");
  14. System.out.println(System.getProperty("user.dir"));
  15. //方式二
  16. System.out.println("方式二");
  17. File directory = new File("");//设定为当前文件夹
  18. try{
  19. System.out.println(directory.getCanonicalPath());//获取标准的路径
  20. System.out.println(directory.getAbsolutePath());//获取绝对路径
  21. }catch(Exception e)
  22. {
  23. e.printStackTrace();
  24. }
  25. //方式三
  26. System.out.println("方式三");
  27. System.out.println(GetPath.class.getResource("/"));
  28. System.out.println(GetPath.class.getResource(""));
  29. //方式4
  30. System.out.println("方式四");
  31. System.out.println(GetPath.class.getClassLoader().getResource(""));
  32. System.out.println(GetPath.class.getClassLoader().getResource("source.xml"));
  33. }
  34. /**
  35. * @param name   文件名  不包含路径
  36. */
  37. public static  String getSrcPath(String name)
  38. {
  39. String result=null;
  40. URL urlpath = GetPath.class.getClassLoader().getResource(name);
  41. String path=urlpath.toString();
  42. //remove the head "file:",if it exists
  43. if(path.startsWith("file"))
  44. {
  45. path=path.substring(5);
  46. }
  47. path.replace("/", File.separator);
  48. result=path;
  49. return result;
  50. }
  51. // filename 文件名 不包含路径
  52. // ...args  文件夹名      可以输入多个文件夹名参数
  53. public static String getParallelPath(String filename,String ...args)
  54. {
  55. String pre=System.getProperty("user.dir");
  56. String path=pre;
  57. for(String arg:args)
  58. {
  59. path+=File.separator+arg;
  60. }
  61. path+=File.separator+filename;
  62. if(path.startsWith("file"))
  63. {
  64. path=path.substring(5);
  65. }
  66. path.replace("/", File.separator);
  67. return path;
  68. }
  69. public static void readFile(String filepath)
  70. {
  71. File file=new File(filepath);
  72. try {
  73. InputStreamReader sr=new InputStreamReader(new FileInputStream(file));
  74. BufferedReader br=new BufferedReader(sr);
  75. String line=null;
  76. while((line=br.readLine())!=null)
  77. {
  78. System.out.println(line);
  79. }
  80. } catch (FileNotFoundException e) {
  81. // TODO Auto-generated catch block
  82. e.printStackTrace();
  83. } catch (IOException e) {
  84. // TODO Auto-generated catch block
  85. e.printStackTrace();
  86. }
  87. }
  88. public static String getPackagePath(String filename)
  89. {
  90. String result=null;
  91. URL urlpath=GetPath.class.getResource("");
  92. String path=urlpath.toString();
  93. if(path.startsWith("file"))
  94. {
  95. path=path.substring(5);
  96. }
  97. path.replace("/", File.separator);
  98. result=path+filename;
  99. return result;
  100. }
  101. //获取WebRoot目录
  102. public static String getWebRootPath()
  103. {
  104. URL urlpath=GetPath.class.getResource("");
  105. String path=urlpath.toString();
  106. if(path.startsWith("file"))
  107. {
  108. path=path.substring(5);
  109. }
  110. if(path.indexOf("WEB-INF")>0)
  111. {
  112. path=path.substring(0,path.indexOf("WEB-INF")-1);
  113. }
  114. path.replace("/", File.separator);
  115. return path;
  116. }
  117. //webroot  WebRoot目录
  118. //filename  文件名
  119. //...args   文件名所在文件夹,多个参数输入
  120. public static String getWebRootFilepath(String webroot,String filename,String ...args)
  121. {
  122. String pre=webroot;
  123. String path=pre;
  124. for(String arg:args)
  125. {
  126. path+=File.separator+arg;
  127. }
  128. path+=File.separator+filename;
  129. if(path.startsWith("file"))
  130. {
  131. path=path.substring(5);
  132. }
  133. path.replace("/", File.separator);
  134. return path;
  135. }
  136. public static void main(String[] args) {
  137. // TODO Auto-generated method stub
  138. //      GetPath.getPath();
  139. //      //1 test
  140. //      System.out.println(GetPath.getSrcPath("source.xml"));
  141. //      GetPath.readFile(GetPath.getSrcPath("source.xml"));
  142. //      //2 test
  143. System.out.println(GetPath.getParallelPath("source.xml", "my file"));
  144. GetPath.readFile(GetPath.getParallelPath("source.xml", "my file"));
  145. //      //3 test
  146. System.out.println(GetPath.getPackagePath("source.xml"));
  147. GetPath.readFile(GetPath.getPackagePath("source.xml"));
  148. }
  149. }

Java文件获取路径方式:的更多相关文章

  1. JAVA中获取路径

    内容来自于snannan_268 关键字: java中获取路径 JAVA中获取路径: 1.jsp中取得路径:   以工程名为TEST为例: (1)得到包含工程名的当前页面全路径:request.get ...

  2. java项目获取路径的几种方式

    第一种: File f = new File(this.getClass().getResource("/").getPath()); System.out.println(f); ...

  3. 浅谈JS中的!=、== 、!==、===的用法和区别 JS中Null与Undefined的区别 读取XML文件 获取路径的方式 C#中Cookie,Session,Application的用法与区别? c#反射 抽象工厂

    浅谈JS中的!=.== .!==.===的用法和区别   var num = 1;     var str = '1';     var test = 1;     test == num  //tr ...

  4. java中获取路径的几种基本的方法

    package com.ygh.blog.realpath; import java.io.File; import java.io.IOException; import java.io.Input ...

  5. Java中获取路径的各种方法

    1. java文件中获得路径 Thread.currentThread().getContextClassLoader().getResource("") //获得资源文件(.cl ...

  6. java中获取路径中的空格处理(%20)问题

    在java中获取文件路径的时候,有时候会获取到空格,但是在中文编码环境下,空格会变成“%20”从而使得路径错误. 解决办法: String path = Parameter.class.getReso ...

  7. java 获取路径与各文件目录的…

    java 获取路径 博客分类: MyJava JavaJSPWebTomcat编程  转至:http://geeksun.iteye.com/blog/356339 (1).request.getRe ...

  8. Java中获取路径的方法_自我分析

    就目前的我来说最常用的两种获取路径的方法是  class.getRecource(filename) 和 class.getclassloader.getRecource(filename) 这两者的 ...

  9. java中获取路径的方法

    在class获取路径的方法,getResource有没有“\”的区别 System.out.println("" + this.getClass().getResource(&qu ...

随机推荐

  1. spring 获取 bean

    不通过注解或者是配置文件怎么获取spring中定义的bean呢?有几个方法: 1.实现ApplicationContextAware <bean class="com.xxx.Spri ...

  2. maximo弹框设置新的功能测试总结

    先介绍下弹框前的准备工作: 1.签名选项——定义系统中可授权的所有功能的唯一标识.定义签名选项是为了授权而已.定义的签名名要和相应的bean类中的方法一致. 2.签名选项中的功能实现,一般都在APPB ...

  3. Ubuntu14.04通过pyenv配置多python

    参考链接: https://github.com/yyuu/pyenv-virtualenv https://github.com/yyuu/pyenv http://seisman.info/pyt ...

  4. iOS 原生态扫描二维码、条形码的功能。

    1.导入AVFoundatin.framework. 2.新建一个viewController,命名为QRScanViewController,用于扫描的界面. h文件如下,设置代理. #import ...

  5. Python学习笔记(二)基本语法

    Class 2 一.交互式编程 交互式编程不需要创建脚本文件,是通过 Python 解释器的交互模式进来编写代码. linux上你只需要在命令行中输入 Python 命令即可启动交互式编程,如下图: ...

  6. bash脚本编程之二 字符串测试及for循环

    shell中大量的测试和比较选项而困惑呢? 这个技巧可以帮助您解密不同类型的文件.算术和字符串测试,这样您就能够知道什么时候使用 test. [ ]. [[ ]].(( )) 或 if-then-el ...

  7. 使用VisualVM监控远程服务器JVM

    VisualVM是JDK自带的一款全能型性能监控和故障分析工具,包括对CPU使用.JVM堆内存消耗.线程.类加载的实时监控,内存dump文件分析,垃圾回收运行情况的可视化分析等,对故障排查和性能调优很 ...

  8. C++ 一个程序获取另一个程序Edit控件的内容

    //一个程序获取另一个程序Edit控件的内容 //根据指定程序的标题名获取改程序窗口的句柄 HWND hWnd=::FindWindow(NULL,"zhang001"); if( ...

  9. BootLoader 详解(1)

    1. Boot Loader的概念 BootLoader就是在操作系统内核运行前之前运行的一段小程序.通过这段小程序,可以初始化硬件设备.建立内存空间映射图,从而将系统的软硬件带到一个合适的状态,以便 ...

  10. 关于C#不同位数相与或,或赋值时,隐藏位数扩展该留意的问题

    __int64 a; char b; a = b; a |= b; 如上情况,当b的最高位为1时,即b=0x80(或更大)时,b在扩展成64过程中会将最高位向高位扩展变成0xfffffffffffff ...