JAvaファイルパスの取得
2509 ワード
ファイルを入手する方法はいろいろありますが、ここでは簡単で実用的なものをいくつか記録します.
1 actionでパスを取得すると
2普通のjavaファイルの中にあります
3 jspでのパスの取得
1 actionでパスを取得すると
// action request ( / \)
HttpServletRequest request = ServletActionContext.getRequest();
String realPath1 = request.getSession().getServletContext().getRealPath("/");
System.out.println(realPath1);//D:\apache-tomcat-6.0.16\webapps\AnliDemo02\
// classes
String path2=Thread.currentThread().getContextClassLoader().getResource("").getPath();
System.out.println(path2);//"/D:/apache-tomcat-6.0.16/webapps/AnliDemo02/WEB-INF/classes/"
// classes
String path3=ShowAllAction.class.getClassLoader().getResource("").getPath();
System.out.println(path3);//"/D:/apache-tomcat-6.0.16/webapps/AnliDemo02/WEB-INF/classes/"
//
String path4=ShowAllAction.class.getResource("").getPath();
System.out.println(path4);//"/D:/apache-tomcat-6.0.16/webapps/AnliDemo02/WEB-INF/classes/net/hncu/action/"
2普通のjavaファイルの中にあります
package pathtest;
public class PathTest {
public static void main(String[] args) {
//
// : ( ) ( java web )
// ,java
//web web (tomcat tomcat \bin)
String relativelyPath=System.getProperty("user.dir");
System.out.println(relativelyPath);//D:\NewWorkSpace\SampleWebTest
// ( )
//1.1) ( java web , )
//(books.xml \src\books.xml; PathTest src )
String path2 = PathTest.class.getClassLoader().getResource("books.xml").toString();
System.out.println(path2);
//file:/D:/NewWorkSpace/SampleWebTest/WebRoot/WEB-INF/classes/books.xml
//1.2)
//(books.xml \src\books.xml, PathTest src )
String path3 = PathTest.class.getResource("/books.xml").toString();
System.out.println(path3);
//file:/D:/NewWorkSpace/SampleWebTest/WebRoot/WEB-INF/classes/books.xml
}
}
3 jspでのパスの取得
<%=application.getRealPath("") %>// "D:\apache-tomcat-6.0.16\webapps\AnliDemo02"
${pageContext.request.contextPath}// "/AnliDemo02"