如何获取WAR文件的大小?

时间:2013-03-12 15:45:59

标签: java servlets war

我想获得我在服务器上运行的WAR文件的大小。我试过谷歌搜索怎么做,但我没有运气。如果我尝试File.length(),它返回0(不是很有用)。

我注意到当我request.getServletContext().getRealPath("/")时,它会返回:

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

有什么办法可以使用这条路径来查找部署的WAR文件的大小?感谢。

4 个答案:

答案 0 :(得分:2)

WAR文件只是一个美化的zip文件,用于将Web应用程序部署到Tomcat。部署后,Tomcat将WAR文件解压缩到一个具有相同名称的目录(没有.war扩展名)。

在您的应用中,request.getServletContext().getRealPath("/")表示解压缩的webapp的根目录的路径,而不是WAR文件。 (这可能是您的File.length调用返回0 - the javadoc的原因,表示目录的长度未定义。)要获取WAR文件的路径和大小,请删除尾部斜杠并添加{{ 1}}扩展名:

.war

答案 1 :(得分: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!");
}

答案 2 :(得分:0)

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

答案 3 :(得分: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。几乎就是我得到的。谢谢=)。

相关问题