Get the size of a resource

后端 未结 3 479
误落风尘
误落风尘 2021-01-18 05:28

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

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

I

3条回答
  •  無奈伤痛
    2021-01-18 05:47

    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.

提交回复
热议问题