Get the size of a resource

I tried answer to this post Ask for length of a file read from Classpath in java but they marked it as duplicated of your question so i give my answer here!

It's possible to get the size of a simple file using:

File file = new File("C:/Users/roberto/Desktop/bar/file.txt");
long length = file.length();
System.out.println("Length: " + length);

When file.txt is packaged in a jar the .length() will return always 0.
So we need to use JarFile:

JarFile jarFile = new JarFile("C:/Users/roberto/Desktop/bar/foo.jar");
Object size = jarFile.getEntry("file.txt").getSize();
System.out.println("Size: " + size.toString())

You can get the compressed size too:

JarFile jarFile = new JarFile("C:/Users/roberto/Desktop/bar/foo.jar");
Object compressedSize = jarFile.getEntry("file.txt").getCompressedSize();
System.out.println("CompressedSize: " + compressedSize);

It's still possible getting the size of a file packaged in a jar using the jar command:

jar tvf Desktop\bar\foo.jar file.txt

Output will be: 5 Thu Jun 27 17:36:10 CEST 2019 file.txt
where 5 is the size.

You can use it in the code:

Process p = Runtime.getRuntime().exec("jar tvf C:/Users/roberto/Desktop/bar/foo.jar file.txt");
StringWriter writer = new StringWriter();
IOUtils.copy(p.getInputStream(), writer, Charset.defaultCharset());
String jarOutput = writer.toString();  

but jdk is required to run the jar command.

Tags:

Java

Scala