首页 > 解决方案 > “文件”类对象大小?

问题描述

我想知道一个File类的对象是否将整个文件加载到主内存中。我想用一大一小两个文件来制作文件类的对象,然后比较这两个对象的大小。但显然,没有直接的方法来确定Java.

标签: javaspringfile

解决方案


File object is just a plain object with a reference to a file path. The referenced file may or may not actually exist in the file system. File object does not hold content of the file.

When you read a file using InputStream (e.g. FileInputStream) or Reader (e.g. FileReader) in conjunction with a Buffer (e.g. BufferedReader), you start reading the actual file content. Now, it is up to you whether you want to keep the whole file content data in the memory or process chunk by chunk and discard it. So, whether or not full file content is loaded into memory depends on your application.

In order to know the file size upfront in bytes, you may do: file.length()

In order to know the file content size after reading, while reading the file store content into byte array (byte[]) and measure the length of the array using mybytes.length.

Update

You have mentioned in the comment that you want to find out the size of File object. File object is just another usual object. Still, if you want to measure the size use java.lang.instrument.Instrumentation#getObjectSize()

Please refer to this article How to use the Java Instrumentation API to understand how to determine object size using java.lang.instrument classes.


推荐阅读