android中关于文件操作的一些方法

package com.lq.android.common.util;


import java.io.BufferedInputStream;

import java.io.BufferedOutputStream;

import java.io.ByteArrayOutputStream;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.InputStream;

import java.text.DecimalFormat;

import java.util.Arrays;

import java.util.Enumeration;

import java.util.zip.ZipEntry;

import java.util.zip.ZipFile;

import java.util.zip.ZipOutputStream;


import com.lq.android.common.application.ApplicationData;


/**

 * 文件操作方法</br>

 * 

 * @作者: 刘倩</br>

 * @时间: 2014年3月29日 上午10:52:45</br>

 * @描述: 全局公用的对文件的操作方法</br>

 */

public class ToolsFile

{

/** 定义buffer的大小 */

private static int BUFFER_SIZE = 1024 * 8;


/**

* 拷贝文件

* @param fromF

*            文件的源路径

* @param toF

*            文件的目标路径

*/

public static void copyFile(File fromF, File toF)

{

FileInputStream fileInputStream = null;

FileOutputStream fileOutputStream = null;

try

{

if (!toF.exists())

{

toF.createNewFile();

}

fileInputStream = new FileInputStream(fromF);

fileOutputStream = new FileOutputStream(toF);

byte[] buffer = new byte[BUFFER_SIZE];

for (int bytesRead = 0; (bytesRead = fileInputStream.read(buffer,

0, buffer.length)) != -1;)

{

fileOutputStream.write(buffer, 0, bytesRead);

}

} catch (Exception e)

{

e.printStackTrace();

} finally

{

try

{

if (fileInputStream != null)

{

fileInputStream.close();

}

if (fileOutputStream != null)

{

fileOutputStream.close();

}

} catch (Exception e)

{

e.printStackTrace();

}

}

}


/**

* 复制一个目录或文件

* @param from

*            需要复制的目录或文件 例如: /home/from

* @param to

*            复制到的目录或文件 例如: /home/to

* @param isCover

*            是否覆盖

*/

public static void copy(String from, String to, boolean isCover)

{

File fromF = new File(from);

File toF = new File(to + "/" + fromF.getName());

copyR(from, toF.getAbsolutePath(), isCover);

}


/**

* 复制目录或文件

* @param from

*            源文件

* @param to

*            目标文件

* @param isCover

*            是否覆盖

*/

private static void copyR(String from, String to, boolean isCover)

{

File fromF = new File(from);

if (fromF.isDirectory())

{

File toF = new File(to);

toF.mkdirs();

File[] files = fromF.listFiles();

for (File file : files)

{

try

{

File toTmpF = new File(toF.getAbsolutePath() + "/"

+ file.getName());

copyR(file.getAbsolutePath(), toTmpF.getAbsolutePath(),

isCover);

} catch (Exception e)

{

e.printStackTrace();

}

}

} else

{

File toF = new File(to);

if (!toF.exists())

{

try

{

toF.createNewFile();

} catch (Exception e)

{

e.printStackTrace();

}

copyFile(fromF, toF);

} else

{

if (isCover)

{

try

{

toF.createNewFile();

} catch (Exception e)

{

e.printStackTrace();

}

copyFile(fromF, toF);

}

}

}

}


/**

* 拷贝assets下的文件

* @param assetFilePath

*            assets的文件路径

* @param to

*            拷贝到的路径

*/

public static void copyAssetFile(String assetFilePath, String to)

{

InputStream inputStream = null;

FileOutputStream fileOutputStream = null;

try

{

inputStream = ApplicationData.globalContext.getAssets().open(

assetFilePath);

File toDir = new File(to);

toDir.mkdirs();

File toFile = new File(

toDir.getAbsolutePath()

+ "/"

+ assetFilePath.substring(assetFilePath

.lastIndexOf("/") + 1));

fileOutputStream = new FileOutputStream(toFile);

byte[] buffer = new byte[BUFFER_SIZE];

for (int bytesRead = 0; (bytesRead = inputStream.read(buffer, 0,

buffer.length)) != -1;)

{

fileOutputStream.write(buffer, 0, bytesRead);

}

} catch (Exception e)

{

e.printStackTrace();

} finally

{

try

{

if (inputStream != null)

{

inputStream.close();

}

if (fileOutputStream != null)

{

fileOutputStream.close();

}

} catch (Exception e)

{

e.printStackTrace();

}

}

}


/**

* 解压zip文件

* @param srcFileFullName

*            需要被解压的文件地址(包括路径+文件名) 例如:/home/kx.apk

* @param targetPath

*            需要解压到的目录 例如:/home/kx

* @return  是否已经被解压

*/

public static boolean unzip(String srcFileFullName, String targetPath)

{

try

{

ZipFile zipFile = new ZipFile(srcFileFullName);

Enumeration<? extends ZipEntry> emu = zipFile.entries();

while (emu.hasMoreElements())

{

ZipEntry entry = (ZipEntry) emu.nextElement();

// 会把目录作为一个file读出一次,所以只建立目录就可以,之下的文件还会被迭代到

if (entry.isDirectory())

{

new File(targetPath + entry.getName()).mkdirs();

continue;

}

BufferedInputStream bis = new BufferedInputStream(

zipFile.getInputStream(entry));

File file = new File(targetPath + entry.getName());

// 加入这个的原因是zipFile读取文件是随机读取的,这就造成可能先读取一个文件,而这个文件所在的目录还没有出现过,所以要建出目录来

File parent = file.getParentFile();

if (parent != null && !parent.exists())

{

parent.mkdirs();

}


FileOutputStream fos = new FileOutputStream(file);

BufferedOutputStream bos = new BufferedOutputStream(fos,

BUFFER_SIZE);


int count;

byte data[] = new byte[BUFFER_SIZE];

while ((count = bis.read(data, 0, BUFFER_SIZE)) != -1)

{

bos.write(data, 0, count);

}

bos.flush();

bos.close();

bis.close();

}

zipFile.close();

return true;

} catch (Exception e)

{

e.printStackTrace();

}

return false;

}


/**

* 压缩文件或目录

* @param srcPath

*            被压缩的文件或目录地址 例如: /home/kx 或 /home/kx/kx.apk

* @param targetFileFullName

*            压缩后的文件地址全程(包括路径+文件名)例如: /home/kx.apk

*/

public static void zip(String srcPath, String targetFileFullName)

{

ZipOutputStream outputStream = null;

FileOutputStream fileOutputStream = null;

try

{

fileOutputStream = new FileOutputStream(targetFileFullName);

outputStream = new ZipOutputStream(fileOutputStream);

zip(outputStream, new File(srcPath), "");

} catch (Exception e)

{

e.printStackTrace();

} finally

{

try

{

if (outputStream != null)

{

outputStream.close();

}

if (fileOutputStream != null)

{

fileOutputStream.close();

}

} catch (Exception e)

{

e.printStackTrace();

}

}

}


/**

* 压缩文件或目录的具体方法

* @param outputStream

*            压缩的流

* @param file

*            文件路径

* @param string

*/

private static void zip(ZipOutputStream out, File file, String base)

{

if (file.isDirectory())

{

File[] fl = file.listFiles();

base = base.length() == 0 ? "" : base + "/";

for (int i = 0; i < fl.length; i++)

{

zip(out, fl[i], base + fl[i].getName());

}

} else

{

FileInputStream in = null;

BufferedInputStream bis = null;

try

{

out.putNextEntry(new ZipEntry(base));

in = new FileInputStream(file);

byte[] buffer = new byte[BUFFER_SIZE];

bis = new BufferedInputStream(in, BUFFER_SIZE);

int size;

while ((size = bis.read(buffer)) != -1)

{

out.write(buffer, 0, size);

}

} catch (Exception e)

{

e.printStackTrace();

} finally

{

try

{

if (in != null)

{

in.close();

}

if (bis != null)

{

bis.close();

}

} catch (Exception e)

{

e.printStackTrace();

}

}

}

}


/**

* 删除文件

* @param filePath

*            删除的文件路径

*/

public static void deleteFile(String filePath)

{

if (null == filePath || 0 == filePath.length())

{

return;

}

try

{

File file = new File(filePath);

if (null != file && file.exists())

{

if (file.isDirectory())// 判断是否为文件夹

{

File[] fileList = file.listFiles();

for (int i = 0; i < fileList.length; i++)

{

String path = fileList[i].getPath();

deleteFile(path);

}

file.delete();

}

if (file.isFile())// 判断是否为文件

{

file.delete();

}

}

} catch (Exception e)

{

e.printStackTrace();

}

}


/**

* 删除目录下的制定文件

* @param filePath

*            文件路径

* @param type

*            文件类型

*/

public static void deleteFileByType(String filePath, String type)

{

if (null == filePath || 0 == filePath.length())

{

return;

}

try

{

File file = new File(filePath);

if (null != file && file.isDirectory())

{

File[] fileList = file.listFiles();

for (int i = 0; i < fileList.length; i++)

{

String path = fileList[i].getPath();

if (null != path && path.endsWith(type))

{

File fileDel = new File(path);

if (null != fileDel && fileDel.exists())

{

fileDel.delete();

}

}

}

}

} catch (Exception e)

{

e.printStackTrace();

}

}


/**

* dirStr1中是否包含所有dirStr2中的内容

* @param dirStr1

*            文件

* @param dirStr2

*            文件

* @return  是否有包含关系

*/

public static boolean isContain(String dirStr1, String dirStr2)

{

File dir1 = new File(dirStr1);

File dir2 = new File(dirStr2);

boolean result = false;

try

{

result = Arrays.asList(dir1.list()).containsAll(

Arrays.asList(dir2.list()));

} catch (Exception e)

{

e.printStackTrace();

}

return result;

}


/**

* InputStream->byte[]方法

* @param inputStream

*            输入流

* @param wantReadLean

*            读多少

* @return  返回字节数组

* @throws  IOException

*             流操作中的io异常

*/

public static final byte[] readBytes(InputStream inputStream,

int wantReadLean) throws IOException

{

ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

byte[] bys = null;

try

{

byte abyte0[] = new byte[1024];

int readLength;

for (int totoalLen = 0; (wantReadLean == 0 || wantReadLean > 0

&& wantReadLean > totoalLen)

&& -1 != (readLength = inputStream.read(abyte0));)

{

totoalLen += readLength;

byteArrayOutputStream.write(abyte0, 0, readLength);

}

bys = byteArrayOutputStream.toByteArray();

} catch (Exception e)

{

e.printStackTrace();

} finally

{

if (byteArrayOutputStream != null)

{

byteArrayOutputStream.close();

}

}

return bys;

}


/**

* 获取文件夹大小

* @param file

*            文件

* @return  返回文件的大小

*/

public static long getFileSize(File file)

{

if (file == null || !file.exists())

{

return 0;

}

long size = 0;

try

{

File[] flist = file.listFiles();

for (int i = 0; i < flist.length; i++)

{

if (flist[i].isDirectory())

{

size += getFileSize(flist[i]);

} else

{

size += flist[i].length();

}

}

} catch (Exception e)

{

e.printStackTrace();

}

return size;

}


/**

* 转换文件大小

* @param size

*            文件大小

* @return  转化后的文件大小

*/

public static String formatFileSize(long size)

{

DecimalFormat df = new DecimalFormat("0.00");

String fileSize = "";

if (size <= 0)

{

fileSize = "0 KB";

} else if (size < 1024)

{

fileSize = df.format((double) size) + " B";

} else if (size < 1048576)

{

fileSize = df.format((double) size / 1024) + " KB";

} else if (size < 1073741824)

{

fileSize = df.format((double) size / 1048576) + " M";

} else

{

fileSize = df.format((double) size / 1073741824) + " G";

}

return fileSize;

}


/**

* 判断某个文件是否存在

* @param path

*            文件路径

* @param name

*            文件名称

* @return  返回该文件是否存在

*/

public static boolean isFileExist(String path, String name)

{

boolean re = false;

try

{

if (null != path)

{

if (new File(path + name).exists())

{

re = true;

}

}

} catch (Exception e)

{

e.printStackTrace();

return false;

}

return re;

}

}


你可能感兴趣的:(file文件操作)