2013-03-12 136 views
2

我想獲取我在服務器上運行的WAR文件的大小。我曾嘗試過使用谷歌搜索如何做,但我沒有任何運氣。如果我嘗試File.length(),它返回0(不是很有幫助)。如何獲取WAR文件的大小?

我注意到,當我做request.getServletContext().getRealPath("/"),它返回:

C:\Program Files\Apache Software Foundation\Tomcat 7.0\webapps\nameofmyapp\

有什麼辦法,我可以用這個路徑來尋找部署在WAR文件的大小?謝謝。

+2

你試過新的文件(WAR文件的完整路徑)和做.length()? – Riking 2013-03-12 15:49:18

+0

是的。它返回0. – snowfi6916 2013-03-12 15:51:04

+0

你的代碼中必須有一個錯誤,.length()對我來說是完美的。 – restricteur 2013-03-12 15:57:58

回答

2

的WAR文件僅僅是用於部署web應用程序到Tomcat一個華而不實的zip文件。部署時,Tomcat將WAR文件解壓縮到具有相同名稱的目錄中(不包​​含.war擴展名)。

在您的應用中,request.getServletContext().getRealPath("/")表示解壓縮webapp的根目錄的路徑,而不是WAR文件。 (這可能是爲什麼你File.length調用返回0 — the javadoc說,作爲該目錄的長度是不確定的。)要獲取WAR文件的路徑和大小,去掉尾隨斜線,並添加.war擴展:

File webappPath = new File(request.getServletContext().getRealPath("/")); 
File warFile = new File(webappPath.getParent(), webappPath.getName() + ".war"); 
int warSize = warFile.length(); 
+1

File(parent,path)構造函數非常有用:3(提交編輯) – Riking 2013-03-12 16:24:09

+0

@Riking同意了,儘管下次你可能應該提供一個更好的原因。 – matts 2013-03-12 16:33:31

+0

這非常適合我。我的代碼如下。謝謝=)。 – snowfi6916 2013-03-12 20:11:15

0

你可以試試這個:

File file = new File("C:/Program Files/Apache Software Foundation/Tomcat 7.0/webapps/nameofmyapp.war"); 
if (file.exists()) { 
    double bytes = file.length(); 
    double kiloBytes = (bytes/1024); 
    double megaBytes = (kiloBytes/1024); 
    double gigaBytes = (megaBytes/1024); 
    double teraBytes = (gigaBytes/1024); 
    double petaBytes = (teraBytes/1024); 
    double exaBytes = (petaBytes/1024); 
    double zettaBytes = (exaBytes/1024); 
    double yottaBytes = (zettaBytes/1024); 

    System.out.println("File Size: " + bytes + " B"); 
    System.out.println("File Size: " + kiloBytes + " KB"); 
    System.out.println("File Size: " + megaBytes + " MB"); 
    System.out.println("File Size: " + gigaBytes + " GB"); 
    System.out.println("File Size: " + teraBytes + " TB"); 
    System.out.println("File Size: " + petaBytes + " PB"); 
    System.out.println("File Size: " + exaBytes + " EB"); 
    System.out.println("File Size: " + zettaBytes + " ZB"); 
    System.out.println("File Size: " + yottaBytes + " YB"); 
} else { 
    System.out.println("Oops!! File does not exists!"); 
} 
+0

這與打印文件的長度沒有什麼不同 – Riking 2013-03-12 16:21:39

0
File file = new File(""C:/Program Files/Apache Software Foundation/Tomcat6.0/webapps/myapp.war""); 
       long filesize = file.length(); 
0

謝謝你的建議傢伙。他們工作,但他們在WAR內部返回文件大小(WAR文件約爲24 MB,並且它返回4096字節)。

無論如何,這是最後的工作代碼:

@Autowired 
ServletContext context; //because Tomcat 6 needs to have ServletContext autowired 

String strWebAppName = context.getRealPath("/"); 
String strWarFile = new File(strWebAppName).getParent() + "/myappname.war"; 
File fileMyApp = new File(strWarFile); 
long fileSize = 0; 
if(fileMyApp.exists()) 
{ 
    fileSize = fileMyApp.length(); 
} 

它返回24671122個字節。謝謝你們的幫助。

編輯:剛纔看到你的帖子matts。幾乎完全是我得到的。謝謝=)。