JAVA文件中获取路径及WEB应用程序获取路径方法

在J2SE中,或者不发布的webapp下测试:html

File file=new File("./text.xml")  发现读取src下面的text.xml文件java

可是当咱们把webapp发不到tomcat下面,你会发现他找不到路径了,他会到tomcat bin文件下面去找。web

其实webapp发布的时候,会把源文件的class放到WEB-INF/classses下面,会把工程中WEB-INF下面的东西放到发布的WEB-INF下面,如jsp,lib等等。tomcat

因此程序要读取配置文件,好比我偶们把配置文件放到conf下面,发现发布后,WEB-INF/classses没有这个配置文件,缘由是这个conf文件只是普通文件夹,必需要和src同样是源文件夹才行。因此配置文件有三种放的方法:app

1 直接放到src下面
webapp

2  创建源的文件夹,如conf,放到下面,其实最后编译都会放到WEB-INF/classses下面,这样放只是为了和普通的src区分jsp

3 放到工程WEB-INF目录下面测试

好比我在src下面放了一个mapping.xml,读取他这样;好比这段带吗在Test类里面spa

String path=Test.class.getClassLoader().getResource("mapping.xml").getPath();.net

File file=new File(path);

这样就搞定了。

这是别人的代码:

package   org.cheng.file; 
import   java.io.File; 
public   class   FileTest{ 
     public   static   void   main(String[]args) throws   Exception{ 
         System.out.println(Thread.currentThread().getContextClassLoader().getResource( "" )); 
         System.out.println(FileTest. class .getClassLoader().getResource( "" )); 
         System.out.println(ClassLoader.getSystemResource( "" )); 
         System.out.println(FileTest. class .getResource( "" )); 
         System.out.println(FileTest. class .getResource( "/" )); //Class文件所在路径 
         System.out.println(newFile( "/" ).getAbsolutePath()); 
         System.out.println(System.getProperty( "user.dir" )); 
    

}

参考博客,这两个颇有用,感谢他们:

http://my.oschina.net/xianggao/blog/85172#OSC_h4_8

http://www.bubuko.com/infodetail-776607.html

相关文章
相关标签/搜索