Ⅰ 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;
//}
}
%>