Android开发中的文件操作工具类FileUtil完整实例
程序员文章站
2022-10-08 23:43:27
本文实例讲述了android开发中的文件操作工具类fileutil。分享给大家供大家参考,具体如下:
package com.ymerp.android.tool...
本文实例讲述了android开发中的文件操作工具类fileutil。分享给大家供大家参考,具体如下:
package com.ymerp.android.tools; import java.io.bufferedreader; import java.io.bytearrayoutputstream; import java.io.file; import java.io.fileinputstream; import java.io.fileoutputstream; import java.io.filereader; import java.io.ioexception; import java.io.inputstream; import java.io.linenumberreader; import java.io.outputstream; import java.io.reader; import java.text.decimalformat; import java.util.arraylist; import java.util.hashmap; import java.util.list; import java.util.map; import android.content.context; import android.graphics.bitmap; import android.graphics.bitmap.config; import android.graphics.bitmapfactory; import android.os.environment; import android.util.log; import android.widget.toast; /** * 文件操作工具 * * @author chen.lin * */ public class fileutil { private static final string tag = "fileutil"; /** * 从sd卡取文件 * * @param filename * @return */ public string getfilefromsdcard(string filename) { bytearrayoutputstream outputstream = null; fileinputstream fis = null; try { outputstream = new bytearrayoutputstream(); file file = new file(environment.getexternalstoragedirectory(), filename); if (environment.media_mounted.equals(environment.getexternalstoragestate())) { fis = new fileinputstream(file); int len = 0; byte[] data = new byte[1024]; while ((len = fis.read(data)) != -1) { outputstream.write(data, 0, len); } } } catch (exception e) { e.printstacktrace(); } finally { try { outputstream.close(); fis.close(); } catch (ioexception e) { } } return new string(outputstream.tobytearray()); } /** * 保存文件到sd * * @param filename * @param content * @return */ public static boolean savecontenttosdcard(string filename, string content) { boolean flag = false; fileoutputstream fos = null; try { file file = new file(environment.getexternalstoragedirectory(), filename); if (environment.media_mounted.equals(environment.getexternalstoragestate())) { fos = new fileoutputstream(file); fos.write(content.getbytes()); flag = true; } } catch (exception e) { e.printstacktrace(); flag = false; } finally { try { fos.close(); } catch (ioexception e) { } } return flag; } /** * 取得文件大小 * * @param f * @return * @throws exception */ @suppresswarnings("resource") public static long getfilesizes(file f) throws exception { long size = 0; if (f.exists()) { fileinputstream fis = null; fis = new fileinputstream(f); size = fis.available(); } else { f.createnewfile(); } return size; } /** * 递归取得文件夹大小 * * @param dir * @return * @throws exception */ public static long getfilesize(file dir) throws exception { long size = 0; file flist[] = dir.listfiles(); for (int i = 0; i < flist.length; i++) { if (flist[i].isdirectory()) { size = size + getfilesize(flist[i]); } else { size = size + flist[i].length(); } } return size; } /** * 转换文件大小 * * @param files * @return */ public static string formetfilesize(long files) { decimalformat df = new decimalformat("#.00"); string filesizestring = ""; if (files < 1024) { filesizestring = df.format((double) files) + "b"; } else if (files < 1048576) { filesizestring = df.format((double) files / 1024) + "k"; } else if (files < 1073741824) { filesizestring = df.format((double) files / 1048576) + "m"; } else { filesizestring = df.format((double) files / 1073741824) + "g"; } return filesizestring; } /** * 递归求取目录文件个数 * * @param f * @return */ public static long getlist(file f) { long size = 0; file flist[] = f.listfiles(); size = flist.length; for (int i = 0; i < flist.length; i++) { if (flist[i].isdirectory()) { size = size + getlist(flist[i]); size--; } } return size; } /** * 在根目录下搜索文件 * * @param keyword * @return */ public static string searchfile(string keyword) { string result = ""; file[] files = new file("/").listfiles(); for (file file : files) { if (file.getname().indexof(keyword) >= 0) { result += file.getpath() + "\n"; } } if (result.equals("")) { result = "找不到文件!!"; } return result; } /** * @detail 搜索sdcard文件 * @param 需要进行文件搜索的目录 * @param 过滤搜索文件类型 * */ public static list<string> search(file file, string[] ext) { list<string> list = new arraylist<string>(); if (file != null) { if (file.isdirectory()) { file[] listfile = file.listfiles(); if (listfile != null) { for (int i = 0; i < listfile.length; i++) { search(listfile[i], ext); } } } else { string filename = file.getabsolutepath(); for (int i = 0; i < ext.length; i++) { if (filename.endswith(ext[i])) { list.add(filename); break; } } } } return list; } /** * 查询文件 * * @param file * @param keyword * @return */ public static list<file> findfile(file file, string keyword) { list<file> list = new arraylist<file>(); if (file.isdirectory()) { file[] files = file.listfiles(); if (files != null) { for (file tempf : files) { if (tempf.isdirectory()) { if (tempf.getname().tolowercase().lastindexof(keyword) > -1) { list.add(tempf); } list.addall(findfile(tempf, keyword)); } else { if (tempf.getname().tolowercase().lastindexof(keyword) > -1) { list.add(tempf); } } } } } return list; } /** * searchfile 查找文件并加入到arraylist 当中去 * * @param context * @param keyword * @param filepath * @return */ public static list<map<string, object>> searchfile(context context, string keyword, file filepath) { list<map<string, object>> list = new arraylist<map<string, object>>(); map<string, object> rowitem = null; int index = 0; // 判断sd卡是否存在 if (environment.getexternalstoragestate().equals(environment.media_mounted)) { file[] files = filepath.listfiles(); if (files.length > 0) { for (file file : files) { if (file.isdirectory()) { if (file.getname().tolowercase().lastindexof(keyword) > -1) { rowitem = new hashmap<string, object>(); rowitem.put("number", index); // 加入序列号 rowitem.put("filename", file.getname());// 加入名称 rowitem.put("path", file.getpath()); // 加入路径 rowitem.put("size", file.length() + ""); // 加入文件大小 list.add(rowitem); } // 如果目录可读就执行(一定要加,不然会挂掉) if (file.canread()) { list.addall(searchfile(context, keyword, file)); // 如果是目录,递归查找 } } else { // 判断是文件,则进行文件名判断 try { if (file.getname().indexof(keyword) > -1 || file.getname().indexof(keyword.touppercase()) > -1) { rowitem = new hashmap<string, object>(); rowitem.put("number", index); // 加入序列号 rowitem.put("filename", file.getname());// 加入名称 rowitem.put("path", file.getpath()); // 加入路径 rowitem.put("size", file.length() + ""); // 加入文件大小 list.add(rowitem); index++; } } catch (exception e) { toast.maketext(context, "查找发生错误!", toast.length_short).show(); } } } } } return list; } /** * 根据后缀得到文件类型 * * @param filename * @param pointindex * @return */ public static string getfiletype(string filename, int pointindex) { string type = filename.substring(pointindex + 1).tolowercase(); if ("m4a".equalsignorecase(type) || "xmf".equalsignorecase(type) || "ogg".equalsignorecase(type) || "wav".equalsignorecase(type) || "m4a".equalsignorecase(type) || "aiff".equalsignorecase(type) || "midi".equalsignorecase(type) || "vqf".equalsignorecase(type) || "aac".equalsignorecase(type) || "flac".equalsignorecase(type) || "tak".equalsignorecase(type) || "wv".equalsignorecase(type)) { type = "ic_file_audio"; } else if ("mp3".equalsignorecase(type) || "mid".equalsignorecase(type)) { type = "ic_file_mp3"; } else if ("avi".equalsignorecase(type) || "mp4".equalsignorecase(type) || "dvd".equalsignorecase(type) || "mid".equalsignorecase(type) || "mov".equalsignorecase(type) || "mkv".equalsignorecase(type) || "mp2v".equalsignorecase(type) || "mpe".equalsignorecase(type) || "mpeg".equalsignorecase(type) || "mpg".equalsignorecase(type) || "asx".equalsignorecase(type) || "asf".equalsignorecase(type) || "flv".equalsignorecase(type) || "navi".equalsignorecase(type) || "divx".equalsignorecase(type) || "rm".equalsignorecase(type) || "rmvb".equalsignorecase(type) || "dat".equalsignorecase(type) || "mpa".equalsignorecase(type) || "vob".equalsignorecase(type) || "3gp".equalsignorecase(type) || "swf".equalsignorecase(type) || "wmv".equalsignorecase(type)) { type = "ic_file_video"; } else if ("bmp".equalsignorecase(type) || "pcx".equalsignorecase(type) || "tiff".equalsignorecase(type) || "gif".equalsignorecase(type) || "jpeg".equalsignorecase(type) || "tga".equalsignorecase(type) || "exif".equalsignorecase(type) || "fpx".equalsignorecase(type) || "psd".equalsignorecase(type) || "cdr".equalsignorecase(type) || "raw".equalsignorecase(type) || "eps".equalsignorecase(type) || "gif".equalsignorecase(type) || "jpg".equalsignorecase(type) || "jpeg".equalsignorecase(type) || "png".equalsignorecase(type) || "hdri".equalsignorecase(type) || "ai".equalsignorecase(type)) { type = "ic_file_image"; } else if ("ppt".equalsignorecase(type) || "doc".equalsignorecase(type) || "xls".equalsignorecase(type) || "pps".equalsignorecase(type) || "xlsx".equalsignorecase(type) || "xlsm".equalsignorecase(type) || "pptx".equalsignorecase(type) || "pptm".equalsignorecase(type) || "ppsx".equalsignorecase(type) || "maw".equalsignorecase(type) || "mdb".equalsignorecase(type) || "pot".equalsignorecase(type) || "msg".equalsignorecase(type) || "oft".equalsignorecase(type) || "xlw".equalsignorecase(type) || "wps".equalsignorecase(type) || "rtf".equalsignorecase(type) || "ppsm".equalsignorecase(type) || "potx".equalsignorecase(type) || "potm".equalsignorecase(type) || "ppam".equalsignorecase(type)) { type = "ic_file_office"; } else if ("txt".equalsignorecase(type) || "text".equalsignorecase(type) || "chm".equalsignorecase(type) || "hlp".equalsignorecase(type) || "pdf".equalsignorecase(type) || "doc".equalsignorecase(type) || "docx".equalsignorecase(type) || "docm".equalsignorecase(type) || "dotx".equalsignorecase(type)) { type = "ic_file_text"; } else if ("ini".equalsignorecase(type) || "sys".equalsignorecase(type) || "dll".equalsignorecase(type) || "adt".equalsignorecase(type)) { type = "ic_file_system"; } else if ("rar".equalsignorecase(type) || "zip".equalsignorecase(type) || "arj".equalsignorecase(type) || "gz".equalsignorecase(type) || "z".equalsignorecase(type) || "7z".equalsignorecase(type) || "gz".equalsignorecase(type) || "bz".equalsignorecase(type) || "zpaq".equalsignorecase(type)) { type = "ic_file_rar"; } else if ("html".equalsignorecase(type) || "htm".equalsignorecase(type) || "java".equalsignorecase(type) || "php".equalsignorecase(type) || "asp".equalsignorecase(type) || "aspx".equalsignorecase(type) || "jsp".equalsignorecase(type) || "shtml".equalsignorecase(type) || "xml".equalsignorecase(type)) { type = "ic_file_web"; } else if ("exe".equalsignorecase(type) || "com".equalsignorecase(type) || "bat".equalsignorecase(type) || "iso".equalsignorecase(type) || "msi".equalsignorecase(type)) { type = "ic_file_exe"; } else if ("apk".equalsignorecase(type)) { type = "ic_file_apk"; } else { type = "ic_file_normal"; } return type; } /** * 改变文件大小显示的内容 * * @param size * @return */ public static string changefilesize(string size) { if (integer.parseint(size) > 1024) { size = integer.parseint(size) / 1024 + "k"; } else if (integer.parseint(size) > (1024 * 1024)) { size = integer.parseint(size) / (1024 * 1024) + "m"; } else if (integer.parseint(size) > (1024 * 1024 * 1024)) { size = integer.parseint(size) / (1024 * 1024 * 1024) + "g"; } else { size += "b"; } return size; } /** * 得到所有文件 * * @param dir * @return */ public static arraylist<file> getallfiles(file dir) { arraylist<file> allfiles = new arraylist<file>(); // 递归取得目录下的所有文件及文件夹 file[] files = dir.listfiles(); for (int i = 0; i < files.length; i++) { file file = files[i]; allfiles.add(file); if (file.isdirectory()) { getallfiles(file); } } logger.i("test", allfiles.size() + ""); return allfiles; } /** * 判断文件mimetype 类型 * * @param f * @return */ public static string getmimetype(file f) { string type = ""; string fname = f.getname(); /* 取得扩展名 */ string end = fname.substring(fname.lastindexof(".") + 1, fname.length()).tolowercase(); /* 依扩展名的类型决定mimetype */ if (end.equalsignorecase("m4a") || end.equalsignorecase("mp3") || end.equalsignorecase("mid") || end.equalsignorecase("xmf") || end.equalsignorecase("ogg") || end.equalsignorecase("wav")) { type = "audio"; } else if (end.equalsignorecase("3gp") || end.equalsignorecase("mp4")) { type = "video"; } else if (end.equalsignorecase("jpg") || end.equalsignorecase("gif") || end.equalsignorecase("png") || end.equalsignorecase("jpeg") || end.equalsignorecase("bmp")) { type = "image"; } else if (end.equalsignorecase("apk")) { /* android.permission.install_packages */ type = "application/vnd.android.package-archive"; } else if (end.equalsignorecase("txt") || end.equalsignorecase("java")) { /* android.permission.install_packages */ type = "text"; } else { type = "*"; } /* 如果无法直接打开,就跳出软件列表给用户选择 */ if (end.equalsignorecase("apk")) { } else { type += "/*"; } return type; } /** * 拷贝文件 * * @param fromfile * @param tofile * @throws ioexception */ public static void copyfile(file fromfile, string tofile) throws ioexception { fileinputstream from = null; fileoutputstream to = null; try { from = new fileinputstream(fromfile); to = new fileoutputstream(tofile); byte[] buffer = new byte[1024]; int bytesread; while ((bytesread = from.read(buffer)) != -1) to.write(buffer, 0, bytesread); // write } finally { if (from != null) try { from.close(); } catch (ioexception e) { log.e(tag, "", e); } if (to != null) try { to.close(); } catch (ioexception e) { log.e(tag, "", e); } } } /** * 创建文件 * * @param file * @return */ public static file createnewfile(file file) { try { if (file.exists()) { return file; } file dir = file.getparentfile(); if (!dir.exists()) { dir.mkdirs(); } if (!file.exists()) { file.createnewfile(); } } catch (ioexception e) { log.e(tag, "", e); return null; } return file; } /** * 创建文件 * * @param path */ public static file createnewfile(string path) { file file = new file(path); return createnewfile(file); }// end method createtext() /** * 删除文件 * * @param path */ public static void deletefile(string path) { file file = new file(path); deletefile(file); } /** * 删除文件 * * @param file */ public static void deletefile(file file) { if (!file.exists()) { return; } if (file.isfile()) { file.delete(); } else if (file.isdirectory()) { file files[] = file.listfiles(); for (int i = 0; i < files.length; i++) { deletefile(files[i]); } } file.delete(); } /** * 向text文件中写入内容 * * @param file * @param content * @return */ public static boolean write(string path, string content) { return write(path, content, false); } public static boolean write(string path, string content, boolean append) { return write(new file(path), content, append); } public static boolean write(file file, string content) { return write(file, content, false); } /** * 写入文件 * * @param file * @param content * @param append * @return */ public static boolean write(file file, string content, boolean append) { if (file == null || stringutil.empty(content)) { return false; } if (!file.exists()) { file = createnewfile(file); } fileoutputstream fos = null; try { fos = new fileoutputstream(file, append); fos.write(content.getbytes()); } catch (exception e) { log.e(tag, "", e); return false; } finally { try { fos.close(); } catch (ioexception e) { log.e(tag, "", e); } fos = null; } return true; } /** * 获得文件名 * * @param path * @return */ public static string getfilename(string path) { if (stringutil.empty(path)) { return null; } file f = new file(path); string name = f.getname(); f = null; return name; } /** * 读取文件内容,从第startline行开始,读取linecount行 * * @param file * @param startline * @param linecount * @return 读到文字的list,如果list.size<linecount则说明读到文件末尾了 */ public static list<string> readfile(file file, int startline, int linecount) { if (file == null || startline < 1 || linecount < 1) { return null; } if (!file.exists()) { return null; } filereader filereader = null; list<string> list = null; try { list = new arraylist<string>(); filereader = new filereader(file); linenumberreader linereader = new linenumberreader(filereader); boolean end = false; for (int i = 1; i < startline; i++) { if (linereader.readline() == null) { end = true; break; } } if (end == false) { for (int i = startline; i < startline + linecount; i++) { string line = linereader.readline(); if (line == null) { break; } list.add(line); } } } catch (exception e) { log.e(tag, "read log error!", e); } finally { if (filereader != null) { try { filereader.close(); } catch (ioexception e) { e.printstacktrace(); } } } return list; } /** * 创建文件夹 * * @param dir * @return */ public static boolean createdir(file dir) { try { if (!dir.exists()) { dir.mkdirs(); } return true; } catch (exception e) { log.e(tag, "create dir error", e); return false; } } /** * 在sd卡上创建目录 * * @param dirname */ public static file creatsddir(string dirname) { file dir = new file(dirname); dir.mkdir(); return dir; } /** * 判断sd卡上的文件是否存在 */ public static boolean isfileexist(string filename) { file file = new file(filename); return file.exists(); } /** * 将一个inputstream里面的数据写入到sd卡中 */ public static file write2sdfrominput(string path, string filename, inputstream input) { file file = null; outputstream output = null; try { creatsddir(path); file = createnewfile(path + "/" + filename); output = new fileoutputstream(file); byte buffer[] = new byte[1024]; int len = -1; while ((len = input.read(buffer)) != -1) { output.write(buffer, 0, len); } output.flush(); } catch (exception e) { e.printstacktrace(); } finally { try { output.close(); } catch (exception e) { e.printstacktrace(); } } return file; } /** * 读取文件内容 从文件中一行一行的读取文件 * * @param file * @return */ public static string readfile(file file) { reader read = null; string content = ""; string result = ""; bufferedreader br = null; try { read = new filereader(file); br = new bufferedreader(read); while ((content = br.readline().tostring().trim()) != null) { result += content + "\r\n"; } } catch (exception e) { e.printstacktrace(); } finally { try { read.close(); br.close(); } catch (exception e) { e.printstacktrace(); } } return result; } /** * 将图片保存到本地时进行压缩, 即将图片从bitmap形式变为file形式时进行压缩, * 特点是: file形式的图片确实被压缩了, 但是当你重新读取压缩后的file为 bitmap是,它占用的内存并没有改变 * * @param bmp * @param file */ public static void compressbmptofile(bitmap bmp, file file) { bytearrayoutputstream baos = new bytearrayoutputstream(); int options = 80;// 个人喜欢从80开始, bmp.compress(bitmap.compressformat.jpeg, options, baos); while (baos.tobytearray().length / 1024 > 100) { baos.reset(); options -= 10; bmp.compress(bitmap.compressformat.jpeg, options, baos); } try { fileoutputstream fos = new fileoutputstream(file); fos.write(baos.tobytearray()); fos.flush(); fos.close(); } catch (exception e) { e.printstacktrace(); } } /** * 将图片从本地读到内存时,进行压缩 ,即图片从file形式变为bitmap形式 * 特点: 通过设置采样率, 减少图片的像素, 达到对内存中的bitmap进行压缩 * @param srcpath * @return */ public static bitmap compressimagefromfile(string srcpath, float pixwidth, float pixheight) { bitmapfactory.options options = new bitmapfactory.options(); options.injustdecodebounds = true;// 只读边,不读内容 bitmap bitmap = bitmapfactory.decodefile(srcpath, options); options.injustdecodebounds = false; int w = options.outwidth; int h = options.outheight; //float pixwidth = 800f;// //float pixheight = 480f;// int scale = 1; if (w > h && w > pixwidth) { scale = (int) (options.outwidth / pixwidth); } else if (w < h && h > pixheight) { scale = (int) (options.outheight / pixheight); } if (scale <= 0) scale = 1; options.insamplesize = scale;// 设置采样率 options.inpreferredconfig = config.argb_8888;// 该模式是默认的,可不设 options.inpurgeable = true;// 同时设置才会有效 options.ininputshareable = true;// 。当系统内存不够时候图片自动被回收 bitmap = bitmapfactory.decodefile(srcpath, options); // return compressbmpfrombmp(bitmap);//原来的方法调用了这个方法企图进行二次压缩 // 其实是无效的,大家尽管尝试 return bitmap; } /** * 指定分辨率和清晰度的图片压缩 */ public void transimage(string fromfile, string tofile, int width, int height, int quality) { try { bitmap bitmap = bitmapfactory.decodefile(fromfile); int bitmapwidth = bitmap.getwidth(); int bitmapheight = bitmap.getheight(); // 缩放图片的尺寸 float scalewidth = (float) width / bitmapwidth; float scaleheight = (float) height / bitmapheight; matrix matrix = new matrix(); matrix.postscale(scalewidth, scaleheight); // 产生缩放后的bitmap对象 bitmap resizebitmap = bitmap.createbitmap(bitmap, 0, 0, bitmapwidth, bitmapheight, matrix, false); // save file file mycapturefile = new file(tofile); fileoutputstream out = new fileoutputstream(mycapturefile); if(resizebitmap.compress(bitmap.compressformat.jpeg, quality, out)){ out.flush(); out.close(); } if(!bitmap.isrecycled()){ bitmap.recycle();//记得释放资源,否则会内存溢出 } if(!resizebitmap.isrecycled()){ resizebitmap.recycle(); } } catch (filenotfoundexception e) { e.printstacktrace(); } catch (ioexception ex) { ex.printstacktrace(); } } }
更多关于android相关内容感兴趣的读者可查看本站专题:《android文件操作技巧汇总》、《android视图view技巧总结》、《android编程之activity操作技巧总结》、《android布局layout技巧总结》、《android开发入门与进阶教程》、《android资源操作技巧汇总》及《android控件用法总结》
希望本文所述对大家android程序设计有所帮助。
上一篇: 自拍45度真的好美