Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the size of a resource

Tags:

java

scala

I'm using getClass().getResourceAsStream(path) to read from bundle resources.

How can I know the file size before reading the entire stream?

I can't access them with getClass().getResource(path).toURI() when it's packaged, so that won't work.

like image 309
Oscar Broman Avatar asked Dec 18 '15 17:12

Oscar Broman


1 Answers

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.

like image 99
Roberto Manfreda Avatar answered Oct 19 '22 01:10

Roberto Manfreda