java文件绝对路径
❶ java 怎么把文件的绝对路径转换成相对路径
服务器中的Java类获得当前路径
Weblogic WebApplication的系统文件根目录是你的weblogic安装所在根目录。
例如:如果你的weblogic安装在c:eaweblogic700…… 那么,你的文件根路径就是c:. 所以,有两种方式能够让你访问你的服务器端的文件:
a.使用绝对路径: 比如将你的参数文件放在c:yourconfigyourconf.properties, 直接使用 new FileInputStream("yourconfig/yourconf.properties");
b.使用相对路径: 相对路径的根目录就是你的webapplication的根路径,即WEB-INF的上一级目录,将你的参数文件放
在yourwebappyourconfigyourconf.properties, 这样使用: new
FileInputStream("./yourconfig/yourconf.properties"); 这两种方式均可,自己选择。
(2)。Tomcat 在类中输出System.getProperty("user.dir");显示的是%Tomcat_Home%/bin
(3)。Resin 不是你的JSP放的相对路径,是JSP引擎执行这个JSP编译成SERVLET 的路径为根。比如用新建文件法测试File f = new File("a.htm"); 这个a.htm在resin的安装目录下
(4)。如何读相对路径哪? 在Java文件中getResource或getResourceAsStream均可
例:getClass()。getResourceAsStream(filePath);//filePath可以是"/filename",这
里的/代表web 发布根路径下WEB-INF/classes 默认使用该方法的路径是:WEB-INF/classes.已经在Tomcat中测试。
❷ java如何获取类的绝对路径
1 用servlet获取
1.1 获取项目的绝对路径
request.getSession().getServletContext().getRealPath("")
1.2 获取浏览器地址
request.getRequestURL()
1.3 获取当前文件的绝对路径
request.getSession().getServletContext().getRealPath(request.getRequestURI())
2.获取当前的classpath路径
String a2=类名.class.getResource("").toString();
String a3=DBConnection.class.getResource("/").toString();
String a4=DBConnection.class.getClassLoader().getResource("").toString();
String t=Thread.currentThread().getContextClassLoader().getResource("").getPath();
//输出很好理解
3、获取文件的绝对路径
String t=Thread.currentThread().getContextClassLoader().getResource("").getPath();
int num=t.indexOf(".metadata");
String path=t.substring(1,num).replace('/', '\\')+"项目名\\WebContent\\文件";
❸ linux下 Java如何获取文件的绝对路径
需要使用路径时,用下面的方法取得项目根目录的绝对路径(Tools为方法类)
public static String getRootPath() {
String classPath = Tools.class.getClassLoader().getResource("/").getPath();
String rootPath = "";
//windows下
if("\\".equals(File.separator)){
rootPath = classPath.substring(1,classPath.indexOf("/WEB-INF/classes"));
rootPath = rootPath.replace("/", "\\");
}
//linux下
if("/".equals(File.separator)){
rootPath = classPath.substring(0,classPath.indexOf("/WEB-INF/classes"));
rootPath = rootPath.replace("\\", "/");
}
return rootPath;
}