由于公司的服务器要转移到linux上,这让我们的项目面临重新部署的问题,下面将linux上部署路径问题说明一下,linux上获取不到路径,而window下则可以正常获取到
下面将几种获取文件路径的方法放上来,以备不时之需
package com.li.servlet;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Properties;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class FileAction extends HttpServlet {
@Override
protected void service(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
String path1=request.getSession().getServletContext().getRealPath("/");
System.out.println(path1);
String path2 = getServletContext().getRealPath("/");
System.out.println(path2);
String path3=getClass().getResource("/").toString();
System.out.println(path3);
String path4=getClass().getClassLoader().getResource("/").toString();
System.out.println(path4);
String realpath = request.getSession().getServletContext().getRealPath("");
try {
Properties p = new Properties();
// 获得文件系统分隔符
String spa = System.getProperty("file.separator");
// 通过绝对路径获得文件然后获得流
String path5=realpath + spa + "WEB-INF" + spa +"classes" + spa + "config.properties";
System.out.println(path5);
} catch (Exception e) {
e.printStackTrace();
}
}
}