1. 获取文件大小
- public static final int MAX_ATTACHMENT_UPLOAD_SIZE = (5 * 1024 * 1024);
- File file = new File("/sdcard/default/aaa.txt");
- long size = file.length(); //获取文件大小,单位为bytes
- if(size > Email.MAX_ATTACHMENT_UPLOAD_SIZE) //判断文件大小,最大5MB = 5 * 1024 * 1024 bytes
- {
- Toast.makeText(this, "File exceed 5MB, too large to attach",Toast.LENGTH_LONG)
- .show();
- }
2. 判断文件后缀
- File folder = new File("/sdcard/data");
- PickerFilter filter = new PickerFilter();
- File [] files = folder.listFiles(filter);
- int fileCount = files.length; //获取当前目录下文件的个数
- String fileName = files[0].getName(); //获取第一个文件的名字
- /* 先将文件名转换为小写,因为endsWith函数会区分大小写,若后缀为.Txt,
- 判断时会出现不匹配于.txt导致判断有误 */
- fileName = fileName.toLowerCase();
- boolean isTxt = fileName.endsWith(".txt");
3. 文件大小 单位转换
- public static String formatSize(float size)
- {
- long kb = 1024;
- long mb = (kb * 1024);
- long gb = (mb * 1024);
- if (size < kb) {
- return String.format("%d B", (int) size);
- }
- else if (size < mb) {
- return String.format("%.2f KB", size / kb); //保留两位小数
- }
- else if (size < gb) {
- return String.format("%.2f MB", size / mb);
- }
- else {
- return String.format("%.2f GB", size / gb);
- }
- }
4. android在SD卡上创建文件保存信息
1)判断是否存在SD卡
2)获取SD卡目录
3)在SD卡目录下创建文件
4)写入信息到文件中
- //判断SD卡是否存在
- boolean sdCardExist = Environment.getExternalStorageState()
- .equals(android.os.Environment.MEDIA_MOUNTED)
- if (sdCardExist)
- {
- //获取SD卡目录
- File sdDir = Environment.getExternalStorageDirectory();
- //在SD卡目录下创建文件smsLog.txt文件,true表示当文件存在时,信息追加在文件尾
- FileWriter fw = new FileWriter( sdDir.toString() + "/smsLog.txt", true);
- //获取当前时间
- Calendar calendar = Calendar.getInstance();
- Date d = calendar.getTime();
- fw.write("短信接收时间:" + d.toString());
- fw.write("/r/n"); //写入换行
- fw.write("短信内容:");
- fw.write("/r/n");
- //关闭文件
- fw.close();
- }