Ⅰ java 项目如何获取项目所在的物理根路径
在Java中获取文件路径是常见的需求,特别是在上传文件操作中。对于Web应用,可以通过多种方式来获取项目的物理根路径。
在Web应用环境中,使用`this.getClass().getClassLoader().getResource("/").getPath()`和`this.getClass().getClassLoader().getResource("").getPath()`可以得到ClassPath的绝对URI路径。例如:
`/D:/jboss-4.2.2.GA/server/default/deploy/hp.war/WEB-INF/classes/`
而`this.getClass().getClassLoader().getResource(".").getPath()`则可以获取项目的绝对路径,例如:
`/D:/jboss-4.2.2.GA/server/default/deploy/hp.war`
另外,使用`this.getClass().getResource("/").getPath()`和`this.getClass().getResource("").getPath()`同样可以得到当前类文件的URI目录,如:
`/D:/jboss-4.2.2.GA/server/default/deploy/hp.war/WEB-INF/classes/com/jebel/helper/`
但`this.getClass().getResource(".").getPath()`在某些情况下可能无法运行。
在本地运行时,`Thread.currentThread().getContextClassLoader().getResource("/").getPath()`和`Thread.currentThread().getContextClassLoader().getResource("").getPath()`同样可以得到ClassPath的绝对URI路径,如:
`/D:/myProjects/hp/WebRoot/WEB-INF/classes/`
而`Thread.currentThread().getContextClassLoader().getResource(".").getPath()`则可以获取项目的绝对路径,如:
`/D:/myProjects/hp/WebRoot/WEB-INF/classes`
另外,`this.getClass().getResource("/").getPath()`和`this.getClass().getResource("").getPath()`可以得到当前类文件的URI目录,如:
`/D:/myProjects/hp/WebRoot/WEB-INF/classes/com/jebel/helper/`
但`this.getClass().getResource(".").getPath()`在某些情况下可能无法运行。
最后,在Web应用程序中,通常使用`ServletContext.getRealPath("/")`方法来获取Web应用程序根目录的绝对路径。此外,`request.getContextPath()`也可以获取到上下文路径。
但在Weblogic中,需要使用`request.getServletContext().getContextPath()`。然而,当将项目打包成war文件部署到Weblogic服务器时,项目内部并没有文件结构的概念,使用上述方式始终会返回null,无法获取路径。目前还没有找到具体的解决方案。
Ⅱ Java web 怎么实现下载啊,求助急急急急急!!
<%@pagelanguage="java"contentType="application/x-msdownload"pageEncoding="gb2312"%>
<%
//关于文件下载时采用文件流输出的方式处理:
//加上response.reset(),并且所有的%>后面不要换行,包括最后一个;
response.reset();//可以加也可以不加
response.setContentType("application/x-download");
//application.getRealPath("/main/mvplayer/CapSetup.msi");获取的物理路径
Stringfiledownload="想办法找到要提供下载的文件的物理路径+文件名";
Stringfiledisplay="给用户提供的下载文件名";
Stringfiledisplay=URLEncoder.encode(filedisplay,"UTF-8");
response.addHeader("Content-Disposition","attachment;filename="+filedisplay);
java.io.OutputStreamoutp=null;
java.io.FileInputStreamin=null;
try
{
outp=response.getOutputStream();
in=newFileInputStream(filenamedownload);
byte[]b=newbyte[1024];
inti=0;
while((i=in.read(b))>0)
{
outp.write(b,0,i);
}
//
outp.flush();
//要加以下两句话,否则会报错
//java.lang.IllegalStateException:getOutputStream()hasalreadybeencalledfor//thisresponse
out.clear();
out=pageContext.pushBody();
}
catch(Exceptione)
{
System.out.println("Error!");
e.printStackTrace();
}
finally
{
if(in!=null)
{
in.close();
in=null;
}
//这里不能关闭
//if(outp!=null)
//{
//outp.close();
//outp=null;
//}
}
%>