目录结构:
project
out
src
readjava
testtxt
files
opts
项目为priject
out目录为class输出目录
src下为文件目录
src下有两个包,files、opts
想通过相对路径获取testtxt的路径
但是用反射只能获取到class,也就是out里的路径
输出后的目录不就是在out里面了,那个里面的和src里面的文件是一样的, getClass()getResource()就可以得到classpath了啊
看看设置的资源文件编译路径
1、利用SystemgetProperty()函数获取当前路径:
Systemoutprintln(SystemgetProperty("userdir"));//userdir指定了当前的路径
2、使用File提供的函数获取当前路径:
File directory = new File("");//设定为当前文件夹
try{
Systemoutprintln(directorygetCanonicalPath());//获取标准的路径
Systemoutprintln(directorygetAbsolutePath());//获取绝对路径
}catch(Exceptin e){}
FilegetCanonicalPath()和FilegetAbsolutePath()大约只是对于new File("")和new
File("")两种路径有所区别。
# 对于getCanonicalPath()函数,“"就表示当前的文件夹,而”“则表示当前文件夹的上一级文件夹
# 对于getAbsolutePath()函数,则不管””、“”,返回当前的路径加上你在new File()时设定的路径
# 至于getPath()函数,得到的只是你在new File()时设定的路径
Java基础知识教程:
第一步: 先获得classpath路径
String classpath = thisgetClass()getResource("/")getPath()replaceFirst("/", "");
这样子可以得到classpath路径,类似于:
F:/projects/JavaStudyParent/study-springmvc-junit-test/target/springmvc-junit-test/WEB-INF/classes/
然后把WEB-INF/classes截取就能获得WebAPP目录啦:
String webappRoot = classpathreplaceAll("WEB-INF/classes/", "");
得到的结果就是:
F:/projects/JavaStudyParent/study-springmvc-junit-test/target/springmvc-junit-test/
通过这个路径你就能获取该文件夹下的所有文件啦
写了一个读取本地文件的方法, File file = new File(htmlFile); FileReader fr = new FileReader(file); BufferedReader br = new BufferedReader(fr); while((s=brreadLine())!=null){ aladd(s); } 在当前类写了main方法测试了一下是可行的, 但是页面某方法想调用该方法,不能实现。 总结问题是:只有放在static方法中可行,在其他地方调用都显示找不到指定文件。 文件结构: 把本地文件放在了web-inf的classes下了,相对路径写的(“/filetxt”); 求教为啥static方法可以,其他地方调用不行,这个函数本身不是静态的啊。
java获取根路径有两种方式:
1)在servlet可以用一下方法取得:
requestgetRealPath(“/”)
例如:filepach = requestgetRealPath(“/”)+”//upload//”;
2)不从jsp,或servlet中获取,只从普通java类中获取:
String path = getClass()getProtectionDomain()getCodeSource()getLocation()getPath();
SAXReader() saxReader = new SAXReader();
if(pathindexOf(“WEB-INF”)>0){
path = pathsubstring(0,pathindexOf(“/WEB-INF/classes”)+16);
// ‘/WEB-INF/classes’为16位
document = saxReaderread(path+filename);
}else{
document = saxReaderread(getClass()getResourceAsStream(filename));
}
1、利用SystemgetProperty()函数获取当前路径:
Systemoutprintln(SystemgetProperty("userdir"));//userdir指定了当前的路径
2、使用File提供的函数获取当前路径:
File directory = new File("");//设定为当前文件夹
try{
Systemoutprintln(directorygetCanonicalPath());//获取标准的路径
Systemoutprintln(directorygetAbsolutePath());//获取绝对路径
}catch(Exceptin e){}
FilegetCanonicalPath()和FilegetAbsolutePath()大约只是对于new File("")和new File("")两种路径有所区别。
# 对于getCanonicalPath()函数,“"就表示当前的文件夹,而”“则表示当前文件夹的上一级文件夹
# 对于getAbsolutePath()函数,则不管””、“”,返回当前的路径加上你在new File()时设定的路径
# 至于getPath()函数,得到的只是你在new File()时设定的路径
比如当前的路径为 C:/test :
File directory = new File("abc");
directorygetCanonicalPath(); //得到的是C:/test/abc
directorygetAbsolutePath(); //得到的是C:/test/abc
direcotrygetPath(); //得到的是abc
File directory = new File("");
directorygetCanonicalPath(); //得到的是C:/test
directorygetAbsolutePath(); //得到的是C:/test/
direcotrygetPath(); //得到的是
File directory = new File("");
directorygetCanonicalPath(); //得到的是C:/
directorygetAbsolutePath(); //得到的是C:/test/
direcotrygetPath(); //得到的是
另外:SystemgetProperty()中的字符串参数如下:
SystemgetProperty()参数大全
# javaversion Java Runtime Environment version
# javavendor Java Runtime Environment vendor
# javavendorurl Java vendor URL
# javahome Java installation directory
# javavmspecificationversion Java Virtual Machine specification version
# javavmspecificationvendor Java Virtual Machine specification vendor
# javavmspecificationname Java Virtual Machine specification name
# javavmversion Java Virtual Machine implementation version
# javavmvendor Java Virtual Machine implementation vendor
# javavmname Java Virtual Machine implementation name
# javaspecificationversion Java Runtime Environment specification version
# javaspecificationvendor Java Runtime Environment specification vendor
# javaspecificationname Java Runtime Environment specification name
# javaclassversion Java class format version number
# javaclasspath Java class path
# javalibrarypath List of paths to search when loading libraries
# javaiotmpdir Default temp file path
# javacompiler Name of JIT compiler to use
# javaextdirs Path of extension directory or directories
# osname Operating system name
# osarch Operating system architecture
# osversion Operating system version
# fileseparator File separator ("/" on UNIX)
# pathseparator Path separator (":" on UNIX)
# lineseparator Line separator ("/n" on UNIX)
# username User’s account name
# userhome User’s home directory
# userdir User’s current working directory
JAVA中获取路径:
1jsp中取得路径:
以工程名为TEST为例:
(1)得到包含工程名的当前页面全路径:requestgetRequestURI()
结果:/TEST/testjsp
(2)得到工程名:requestgetContextPath()
结果:/TEST
(3)得到当前页面所在目录下全名称:requestgetServletPath()
结果:如果页面在jsp目录下 /TEST/jsp/testjsp
(4)得到页面所在服务器的全路径:applicationgetRealPath("页面jsp")
结果:D:/resin/webapps/TEST/testjsp
(5)得到页面所在服务器的绝对路径:absPath=new javaioFile(applicationgetRealPath(requestgetRequestURI()))getParent();
结果:D:/resin/webapps/TEST
2在类中取得路径:
(1)类的绝对路径:ClassclassgetClass()getResource("/")getPath()
结果:/D:/TEST/WebRoot/WEB-INF/classes/pack/
(2)得到工程的路径:SystemgetProperty("userdir")
结果:D:/TEST
3在Servlet中取得路径:
(1)得到工程目录:requestgetSession()getServletContext()getRealPath("") 参数可具体到包名。
结果:E:/Tomcat/webapps/TEST
(2)得到IE地址栏地址:requestgetRequestURL()
结果:>
java项目中文件的路径-方法大全
一、 相对路径的获得
说明:相对路径(即不写明时候到底相对谁)均可通过以下方式获得(不论是一般的java项目还是web项目)
SystemgetProperty("userdir");
上述相对路径中,java项目中的文件是相对于项目的根目录web项目中的文件路径视不同的web服务器不同而不同(tomcat是相对于tomcat安装目录\bin)
二 类加载目录的获得(即当运行时某一类时获得其装载目录)
11)通用的方法一(不论是一般的java项目还是web项目,先定位到能看到包路径的第一级目录)
InputStreamis=TestActionclassgetClassLoader()getResourceAsStream("testtxt"); (testtxt文件的路径为 项目名\src\testtxt;类TestPath所在包的第一级目录位于src目录下)
上式中将TestPath,testtxt替换成对应成相应的类名和文件名字即可
12)通用方法二 (此方法和11中的方法类似,不同的是此方法必须以'/'开头) InputStream is=Test1classgetResourceAsStream("/testtxt");
(testtxt文件的路径为 项目名\src\testtxt,类Test1所在包的第一级目录位于src目录下)
三 web项目根目录的获得(发布之后)
1 从servlet出发
可建立一个servlet在其的init方法中写入如下语句(没有请求的话会抛空指针导常)
ServletContext s1=thisgetServletContext();
String temp=s1getRealPath("/"); (关键)
结果形如:F:\tomcat-6036\webapps\test\(test为项目名字)
如果是调用了s1getRealPath("")则输出F:\tomcat-6036\webapps\test(少了一个"\")
2 从>
String path=requestgetSession()getServletContext()getRealPath("/");
结果形如: F:\tomcat-6036\webapps\test\
四 classpath的获取(在Eclipse中为获得src或者classes目录的路径),放在监听器,可以窗口启动获取路径
方法一 ThreadcurrentThread()getContextClassLoader()getResource("")getPath()
String path = ThreadcurrentThread()getContextClassLoader()
getResource("")getPath();
Systemoutprintln("path========" + path);输出: path========/F:/tomcat-6036/webapps/test/WEB-INF/classes/
方法二 JdomParseclassgetClassLoader()getResource("")getPath() (JdomParse为src某一个包中的类,下同)
eg:String p1=JdomParseclassgetClassLoader()getResource("")getPath();
Systemoutprintln("JdomParseclassgetClassLoader()getResource--"+p1);
输出:JdomParseclassgetClassLoader()getResource-/F:/tomcat-6036/webapps/test/WEB-INF/classes/
另外,如果想把文件放在某一包中,则可以 通过以下方式获得到文件(先定位到该包的最后一级目录)
eg String p2=JdomParseclassgetResource("")getPath();
Systemoutprintln("JdomParseclassgetResource---"+p2);
输出:JdomParseclassgetResource--/F:/tomcat-6036/webapps/test/WEB-INF/classes/
(JdomParse为src目录下jdom包中的类)
四 属性文件的读取:
方法 一
InputStream in = lnewBufferedInputStream( new FileInputStream(name));
Properties p = new Properties(); pload(in);
注意路径的问题,做执行之后就可以调用pgetProperty("name")得到对应属性的值
方法二
Locale locale =LocalegetDefault();
ResourceBundle localResource = ResourceBundlegetBundle("test/propertiesTest",locale);
String value = localResourcegetString("test");
Systemoutprintln("ResourceBundle: " + value);
工程src目录下propertiesTestproperties(名字后缀必须为properties)文件内容如下:
test=hello word
不通过Servlet获取路径
第一种实现
Java代码
URL url = ClassLoadergetSystemClassLoader()getResource("/");
File file =new File(urlgetPath());
File parentFile =new File(filegetParent());
Systemoutprintln("webRoot:"+parentFilegetParent());
第二种实现
首先写一个接听类 (推荐使用,容器启动时就执行,不会抛空指针异常,适合做定时器任务来删除服务器文件的路径)
Java代码:
package comchinacreatorreportlistener;
import javaxservletServletContext;
import javaxservletServletContextEvent;
import javaxservletServletContextListener;
/
@authorxiaoqunyi
/
public class PathListener implementsServletContextListener {
private staticServletContext servletContext;
public voidcontextDestroyed(ServletContextEvent sce) {
thisservletContext= scegetServletContext();
Systemoutprintln("path=======:"+servletContextgetRealPath("/"));
}
public voidcontextInitialized(ServletContextEvent arg0) {
}
}
在webxml中加入如下配置
Java代码 :
<listener>
<listener-class>comchinacreatorreportlistenerPathListener</listener-class>
</listener>
五、Java中的getResourceAsStream有以下几种:
1 ClassgetResourceAsStream(String path) : path 不以’/'开头时默认是从此类所在的包下取资源,以’/'开头则是从ClassPath根下获取。其只是通过path构造一个绝对路径,最终还是由 ClassLoader(类加载器)(获取资源)
2 ClassgetClassLoadergetResourceAsStream(String path) :默认则是从ClassPath根下获取,path不能以’/'开头,最终是由ClassLoader获取资源。
3 ServletContext getResourceAsStream(String path):默认从WebAPP根目录下取资源,Tomcat下path是否以’/'开头无所谓,当然这和具体的容器实现有关。
4 Jsp下的application内置对象就是上面的ServletContext的一种实现。
其次,getResourceAsStream 用法大致有以下几种:
第一: 要加载的文件和class文件在同一目录下,例如:comxy 下有类meclass ,同时有资源文件myfilexml
那么,应该有如下代码:
meclassgetResourceAsStream("myfilexml");
第二:在meclass目录的子目录下,例如:comxy 下有类meclass ,同时在 comxyfile 目录下有资源文件myfilexml
那么,应该有如下代码:
meclassgetResourceAsStream("file/myfilexml");
第三:不在meclass目录下,也不在子目录下,例如:comxy 下有类meclass ,同时在 comxfile 目录下有资源文件myfilexml
那么,应该有如下代码:
meclassgetResourceAsStream("/com/x/file/myfilexml");
总结一下,可能只是两种写法
第一:前面有 “ / ”
“ / ”代表了工程的根目录,例如工程名叫做myproject,“ / ”代表了myproject
meclassgetResourceAsStream("/com/x/file/myfilexml");
第二:前面没有 “ / ”
代表当前类的目录
meclassgetResourceAsStream("myfilexml");
meclassgetResourceAsStream("file/myfilexml");
以上就是关于java项目根目录和类路径问题全部的内容,包括:java项目根目录和类路径问题、如何获得当前Java文件的路径、如何在java web项目中获得相对路径等相关内容解答,如果想了解更多相关内容,可以关注我们,你们的支持是我们更新的动力!
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)