android文件处理
时间:2010-08-23 来源:朱宇华
获取文件大小
- 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();
- }
判断文件后缀
- 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" );
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();
- }
相关阅读 更多 +