获取普通Java对象大小

缓存对象需要知道对象占用空间的大小,可以事先设置好每种类型的大小,此方法对普通的对象起效,Jive论坛中的对象也是采用这种办法来获取对象的大小的(取自Jive).

 

  1. public class CacheSizes {  
  2.     /** 
  3.      * Returns the size in bytes of a basic Object. This method should only 
  4.      * be used for actual Object objects and not classes that extend Object. 
  5.      * 
  6.      * @return the size of an Object. 
  7.      */  
  8.     public static int sizeOfObject() {  
  9.         return 4;  
  10.     }  
  11.     /** 
  12.      * Returns the size in bytes of a String. 
  13.      * 
  14.      * @param string the String to determine the size of. 
  15.      * @return the size of a String. 
  16.      */  
  17.     public static int sizeOfString(String string) {  
  18.         if (string == null) {  
  19.             return 0;  
  20.         }  
  21.         return 4 + string.length()*2;  
  22.     }  
  23.     /** 
  24.      * Returns the size in bytes of a primitive int. 
  25.      * 
  26.      * @return the size of a primitive int. 
  27.      */  
  28.     public static int sizeOfInt() {  
  29.         return 4;  
  30.     }  
  31.     /** 
  32.      * Returns the size in bytes of a primitive char. 
  33.      * 
  34.      * @return the size of a primitive char. 
  35.      */  
  36.     public static int sizeOfChar() {  
  37.         return 2;  
  38.     }  
  39.     /** 
  40.      * Returns the size in bytes of a primitive boolean. 
  41.      * 
  42.      * @return the size of a primitive boolean. 
  43.      */  
  44.     public static int sizeOfBoolean() {  
  45.         return 1;  
  46.     }  
  47.     /** 
  48.      * Returns the size in bytes of a primitive long. 
  49.      * 
  50.      * @return the size of a primitive long. 
  51.      */  
  52.     public static int sizeOfLong() {  
  53.         return 8;  
  54.     }  
  55.     /** 
  56.      * Returns the size in bytes of a primitive double. 
  57.      * 
  58.      * @return the size of a primitive double. 
  59.      */  
  60.     public static int sizeOfDouble() {  
  61.         return 8;  
  62.     }  
  63.     /** 
  64.      * Returns the size in bytes of a Date. 
  65.      * 
  66.      * @return the size of a Date. 
  67.      */  
  68.     public static int sizeOfDate() {  
  69.         return 12;  
  70.     }  
  71.     /** 
  72.      * Returns the size in bytes of a Properties object. All properties and 
  73.      * property names must be Strings. 
  74.      * 
  75.      * @param properties the Properties object to determine the size of. 
  76.      * @return the size of a Properties object. 
  77.      */  
  78.     public static int sizeOfProperties(Properties properties) {  
  79.         if (properties == null) {  
  80.             return 0;  
  81.         }  
  82.         //Base properties object  
  83.         int size = 36;  
  84.         //Add in size of each property  
  85.         Enumeration enum = properties.elements();  
  86.         while(enum.hasMoreElements()) {  
  87.             String prop = (String)enum.nextElement();  
  88.             size += sizeOfString(prop);  
  89.         }  
  90.         //Add in property names  
  91.         enum = properties.propertyNames();  
  92.         while(enum.hasMoreElements()) {  
  93.             String prop = (String)enum.nextElement();  
  94.             size += sizeOfString(prop);  
  95.         }  
  96.         return size;  
  97.     }  
  98.     /** 
  99.      * Returns the size in bytes of a Map object. All keys and 
  100.      * values <b>must be Strings</b>. 
  101.      * 
  102.      * @param map the Map object to determine the size of. 
  103.      * @return the size of the Map object. 
  104.      */  
  105.     public static int sizeOfMap(Map map) {  
  106.         if (map == null) {  
  107.             return 0;  
  108.         }  
  109.         //Base map object -- should be something around this size.  
  110.         int size = 36;  
  111.         //Add in size of each value  
  112.         Iterator iter = map.values().iterator();  
  113.         while(iter.hasNext()) {  
  114.             String value = (String)iter.next();  
  115.             size += sizeOfString(value);  
  116.         }  
  117.         //Add in each key  
  118.         iter = map.keySet().iterator();  
  119.         while(iter.hasNext()) {  
  120.             String key = (String)iter.next();  
  121.             size += sizeOfString(key);  
  122.         }  
  123.         return size;  
  124.     }  
  125. }  

点击打开链接
<think>好的,我现在需要解决用户关于如何使用Java中的File类来获取文件大小的问题。首先,我得回顾一下Java中File类的方法。用户提到了几个引用,其中引用[3]明确提到了File类的length()方法,这个方法返回文件的大小。我应该先确认这个方法的具体用法。 用户提供的引用[3]指出,length()函数属于File类,返回文件的长整型数值,单位是字节。如果文件不存在或出现异常,会返回0L。所以正确的步骤应该是创建一个File对象,然后调用其length()方法。需要注意的是,这个方法可能不会总是返回实际文件系统的大小,特别是对于非普通文件的情况,比如稀疏文件或者压缩文件,这时候结果可能不准确。这点在引用[1]中也有提到,Files.size()方法可能会有类似的问题。 接下来,我应该考虑是否需要处理异常。因为当文件无法访问时,可能会抛出安全异常,但根据引用[3],length()在文件不存在时返回0,所以可能不需要显式的异常处理,但最好检查文件是否存在和是否为文件,以避免错误的结果。例如,如果路径是一个目录,length()的返回值可能不可靠,这时候应该提醒用户检查。 然后,我需要对比Files类的size()方法,如引用[1]所述,这个方法属于java.nio.file.Files,需要Path对象作为参数。这可能是一个替代方案,但用户特别询问的是File类的方法,所以应该优先介绍File.length(),然后可以提到Files.size()作为补充,但需要转换File到Path,或者使用toPath()方法。 代码示例方面,用户希望看到具体的用法。因此,我应该提供一个简单的例子,展示如何创建File实例,检查是否存在以及是否是文件,然后调用length()获取大小。同时,应该指出需要处理可能的安全权限问题,尽管在大多数情况下可能不会遇到。 用户的问题可能还涉及到单位转换,比如将字节转换为KB或MB,所以在示例中可以添加这样的转换,帮助用户更好地理解结果。同时,需要注意处理文件不存在的情况,避免返回错误的大小。 最后,需要确保回答结构清晰,分步骤说明,并引用相关的资料,如引用[3]来支持回答的正确性。此外,生成的相关问题应该围绕其他获取文件大小的方法、对比不同方法的差异,以及处理大文件时的注意事项,这样用户可以有进一步的了解。</think>在Java中,使用`File`类获取文件大小可通过`length()`方法实现。以下是具体步骤和注意事项: --- ### 一、核心方法:`File.length()` 1. **方法功能** 返回文件占用的字节数,若文件不存在或无法访问则返回`0L`[^3]。 2. **使用步骤** ```java import java.io.File; public class FileSizeExample { public static void main(String[] args) { // 创建File对象 File file = new File("path/to/your/file.txt"); // 检查文件是否存在且为普通文件 if (file.exists() && file.isFile()) { long fileSize = file.length(); System.out.println("文件大小: " + fileSize + " 字节"); System.out.println("转换为KB: " + (fileSize / 1024) + " KB"); } else { System.out.println("文件不存在或路径指向目录"); } } } ``` 3. **注意事项** - 若路径指向**目录**,返回值是未定义的[^3] - 文件大小可能受系统压缩或稀疏文件影响[^1] --- ### 二、替代方案:`Files.size()` 若使用`java.nio.file.Files`类,可调用`size(Path path)`方法,但需先将`File`转换为`Path`: ```java import java.nio.file.Files; import java.nio.file.Path; import java.io.File; Path path = new File("file.txt").toPath(); long size = Files.size(path); // 需处理IOException ``` 此方法更适用于NIO操作,但需要处理异常。 --- ### 三、两种方法的对比 | 特性 | `File.length()` | `Files.size()` | |---------------------|-----------------------|-----------------------| | 所属类库 | `java.io.File` | `java.nio.file.Files` | | 异常处理 | 无异常(返回0L) | 需处理`IOException` | | 对目录的返回值 | 未定义 | 直接抛出异常 | | 文件系统特性支持 | 依赖系统实现 | 明确说明可能差异 | ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值