jsp中獲取當前目錄的方法

字號:


    本文實例講述了jsp中獲取當前目錄的實現方法,分享給大家供大家參考。具體實現方法如下:
    1、利用System.getProperty()函數獲取當前路徑:
    代碼如下:
    System.out.println(System.getProperty("user.dir"));//user.dir指定了當前的路徑
    2、使用File提供的函數獲取當前路徑:
    代碼如下:
    File directory = new File("");//設定為當前文件夾
    try{
    System.out.println(directory.getCanonicalPath());//獲取標準的路徑
    System.out.println(directory.getAbsolutePath());//獲取絕對路徑
    }catch(Exceptin e){}
    File.getCanonicalPath()和File.getAbsolutePath()大約只是對于new File(".")和new File("..")兩種路徑有所區(qū)別。
    # 對于getCanonicalPath()函數,“."就表示當前的文件夾,而”..“則表示當前文件夾的上一級文件夾
    # 對于getAbsolutePath()函數,則不管”.”、“..”,返回當前的路徑加上你在new File()時設定的路徑
    # 至于getPath()函數,得到的只是你在new File()時設定的路徑
    比如當前的路徑為 C:test :
    代碼如下:
    File directory = new File("abc");
    directory.getCanonicalPath(); //得到的是C:testabc
    directory.getAbsolutePath(); //得到的是C:testabc
    direcotry.getPath(); //得到的是abc
    File directory = new File(".");
    directory.getCanonicalPath(); //得到的是C:test
    directory.getAbsolutePath(); //得到的是C:test.
    direcotry.getPath(); //得到的是.
    File directory = new File("..");
    directory.getCanonicalPath(); //得到的是C:
    directory.getAbsolutePath(); //得到的是C:test..
    direcotry.getPath(); //得到的是..
    獲取 JAVA 程序當前的工作目錄
    代碼如下:
    File file = new File("t.tmp");
    String fullpath = file.getAbsolutePath();
    ① request.getRealPath:
    方法:request.getRealPath("/")
    得到的路徑:C:Program FilesApache Software FoundationTomcat 5.5webappsstrutsTest
    方法:request.getRealPath(".")
    得到的路徑:C:Program FilesApache Software FoundationTomcat 5.5webappsstrutsTest.
    方法:request.getRealPath("")
    得到的路徑:C:Program FilesApache Software FoundationTomcat 5.5webappsstrutsTest
    方法:request.getRealPath("web.xml")
    得到的路徑:C:Program FilesApache Software FoundationTomcat 5.5webappsstrutsTestweb.xml
    ② request.getParameter("");
    ActionForm.getMyFile();
    方法:String filepath = request.getParameter("myFile");
    得到的路徑:D:VSS安裝目錄users.txt
    方法:String filepath = ActionForm.getMyFile();
    得到的路徑:D:VSS安裝目錄users.txt
    希望本文所述對大家的jsp程序設計有所幫助。