android开发中文件操作工具类FileUtils
package com.file.util;
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;
public class FileUtils {
private static final String TAG = "FileUtils";
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());
}
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;
}
@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;
}
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;
}
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;
}
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;
}
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;
}
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;
}
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;
}
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;
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;
}
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;
}
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;
}
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;
}
public static String getMIMEType(File f) {
String type = "";
String fName = f.getName();
String end = fName.substring(fName.lastIndexOf(".") + 1, fName.length()).toLowerCase();
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")) {
type = "application/vnd.android.package-archive";
} else if (end.equalsIgnoreCase("txt") || end.equalsIgnoreCase("java")) {
type = "text";
} else {
type = "*";
}
if (end.equalsIgnoreCase("apk")) {
} else {
type += "/*";
}
return type;
}
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);
} 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);
}
}
}
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;
}
public static File createNewFile(String path) {
File file = new File(path);
return createNewFile(file);
}
public static void deleteFile(String path) {
File file = new File(path);
deleteFile(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();
}
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);
}
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;
}
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;
}