File類有兩個常用方法可以得到檔案路徑一個是:getCanonicalPath(),另一個是:getAbsolutePath(),可以透過File類的實例調用這兩個方法例如file.getAbsolutePath()其中file是File的實例對象。下面是一個具體例子:
public class PathTest
{
public static void main(String[] args)
{
File file = new File(".srcbaidu");
System.out.println(file.getAbsolutePath());
try
{
System.out.println(file.getCanonicalPath());
} catch (IOException e)
{
e.printStackTrace();
}
}
}
getAbsolutePath()和getCanonicalPath()的不同之處在於,getCanonicalPath()得到的是一個規範的路徑,而getAbsolutePath()是用構造File對象的路徑+當前工作目錄。例如在上面的例子中.(點號)代表當前目錄。getCanonicalPath()就會把它解析爲當前目錄但是getAbsolutePath()會把它解析成爲目錄名字(目錄名字是點號)。
下面是上面程序在我電腦上的輸出:
G:xhuojkonw.srcbaidu
G:xhuojkonwsrcbaidu
2. java獲取絕對路徑方法怎麼寫1. Class中獲得絕對路徑的方法
使用System.getProperty(user.dir")即可獲取到當前工程所在位置的絕對路徑。
使用內核ClassLoader提供的getSystemResource("")方法也可以或得到絕對路徑。
2. JSP中獲得絕對路徑的方法
獲得檔案絕對路徑 的方法: application.getRealPath(request.getRequestURI());
當前web應用的絕對路徑 :application.getRealPath("/");
3. java 如何獲取檔案路徑public void doGet(HttpServletRequest request ,HttpServletResponse response ) throws ServletException ,IOException{ OutputStream out;//輸出響應正文的輸出流 InputStream in; //讀取本地檔案的輸入流//獲取filename 請求參數String filename =requeset.getParameter("filename"); if(filename==null){ out=response.getOutputStream(); out.write("please input filename.".getBytes()); out.close;return;} //獲得讀取本地檔案的輸入流in=getServletContext().getResourceAsStream("/store"+filename);int length=in.available();}。