javalinux獲取路徑怎麼寫
一般文件路徑在windows中用 表示,但是在其他系統平台下比如linux中就不是 所以java給我們提供了一個與平台無關的表示路徑的常量 File.separator在windows中則表示 比如現在有一個文件在D:javasrcmyjava中, 如何用絕對路徑訪問呢? 現在建立一個目錄: File fDir=new File(File.separator); //File.separator表示根目錄,比如現在就表示在D盤下。
String strFile="java"+File.separator+"src"+File.separator+"myjava"; //這個就是絕對路徑 File f=new File(fDir,strFile);。
2. java在linux下操作文件路徑怎麼寫一般文件路徑在windows中用 表示,但是在其他系統平台下比如linux中就不是 所以java給我們提供了一個與平台無關的表示路徑的常量 File.separator在windows中則表示 比如現在有一個文件在D:javasrcmyjava中, 如何用絕對路徑訪問呢?
現在建立一個目錄:
File fDir=new File(File.separator); //File.separator表示根目錄,比如現在就表示在D盤下。
String strFile="java"+File.separator+"src"+File.separator+"myjava"; //這個就是絕對路徑
File f=new File(fDir,strFile);
3. 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;
}
4. java如何獲得linux下web路徑java獲取根路徑有兩種方式:
1),在servlet可以用一下方法取得:
request.getRealPath(“/”) 例如:filepach = request.getRealPath(“/”) ”//upload//”;
2),不從jsp,或servlet中獲取,只從普通java類中獲取:
String path =
getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
SAXReader() saxReader = new SAXReader();
if(path.indexOf(“WEB-INF”)>0){
path = path.substring(0,path.indexOf(“/WEB-INF/classes”) 16);
// '/WEB-INF/classes'為16位
document = saxReader.read(path filename);
}else{
document = saxReader.read(getClass().getResourceAsStream(filename));
}
weblogic tomcat 下都有效
String path =
getClass().getProtectionDomain().getCodeSource().getLocation().getPath();