文件处理

1. 获取文件大小

[c-sharp]  view plain copy
  1. public static final int MAX_ATTACHMENT_UPLOAD_SIZE = (5 * 1024 * 1024);  
  2.   
  3. File file = new File("/sdcard/default/aaa.txt");   
  4. long size =  file.length();  //获取文件大小,单位为bytes  
  5. if(size > Email.MAX_ATTACHMENT_UPLOAD_SIZE)  //判断文件大小,最大5MB = 5 * 1024 * 1024 bytes  
  6. {  
  7.      Toast.makeText(this"File exceed 5MB, too large to attach",Toast.LENGTH_LONG)  
  8.                     .show();          
  9. }  

 

2. 判断文件后缀

[c-sharp]  view plain copy
  1. File folder = new File("/sdcard/data");  
  2. PickerFilter filter = new PickerFilter();  
  3. File [] files = folder.listFiles(filter);  
  4. int fileCount = files.length;    //获取当前目录下文件的个数  
  5. String fileName = files[0].getName(); //获取第一个文件的名字  
  6.   
  7. /* 先将文件名转换为小写,因为endsWith函数会区分大小写,若后缀为.Txt, 
  8.    判断时会出现不匹配于.txt导致判断有误 */  
  9. fileName = fileName.toLowerCase();  
  10. boolean isTxt = fileName.endsWith(".txt");   

 

3. 文件大小 单位转换

[c-sharp]  view plain copy
  1. public static String formatSize(float size)  
  2.  {  
  3.      long kb = 1024;  
  4.      long mb = (kb * 1024);  
  5.      long gb  = (mb * 1024);  
  6.      if (size < kb) {  
  7.          return String.format("%d B", (int) size);  
  8.      }  
  9.      else if (size < mb) {  
  10.          return String.format("%.2f KB", size / kb); //保留两位小数  
  11.      }  
  12.      else if (size < gb) {  
  13.          return String.format("%.2f MB", size / mb);  
  14.      }  
  15.      else {  
  16.          return String.format("%.2f GB", size / gb);  
  17.      }  
  18.  }  

 

4. android在SD卡上创建文件保存信息

     1)判断是否存在SD卡

     2)获取SD卡目录

     3)在SD卡目录下创建文件

     4)写入信息到文件中

[c-sharp]  view plain copy
  1. //判断SD卡是否存在  
  2. boolean sdCardExist = Environment.getExternalStorageState()  
  3.                       .equals(android.os.Environment.MEDIA_MOUNTED)  
  4. if (sdCardExist)  
  5. {                                 
  6.     //获取SD卡目录  
  7.     File sdDir = Environment.getExternalStorageDirectory();  
  8.     //在SD卡目录下创建文件smsLog.txt文件,true表示当文件存在时,信息追加在文件尾  
  9.     FileWriter fw = new FileWriter( sdDir.toString() + "/smsLog.txt"true);   
  10.     //获取当前时间  
  11.     Calendar calendar = Calendar.getInstance();  
  12.     Date d = calendar.getTime();  
  13.   
  14.     fw.write("短信接收时间:" + d.toString());  
  15.     fw.write("/r/n"); //写入换行    
  16.      fw.write("短信内容:");  
  17.     fw.write("/r/n");  
  18.        
  19.     //关闭文件  
  20.     fw.close();           
  21.   }  
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值