Android , Java 文件操作类

本文介绍了文件复制、创建、删除、重命名、目录创建等基本操作,涵盖了文件信息判断、文件后缀识别、文件类型识别、文件夹递归复制、文件复制、文件夹删除等功能。
// 2012-4-18下午07:49:44

package com.su.funycard.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.util.Log;

import com.su.funycard.bean.PicFileBean;

public class FileUtil {

	// 复制文件
	public static void copyFile(String ssourceFile, String stargetFile) {
		String folderpath = stargetFile.substring(0,
				stargetFile.lastIndexOf("/"));
		FileUtil.createFolder(folderpath);

		File sourceFile = new File(ssourceFile);
		File targetFile = new File(stargetFile);

		try {
			FileInputStream input = new FileInputStream(sourceFile);

			BufferedInputStream inBuff = new BufferedInputStream(input);

			// 新建文件输出流并对它进行缓冲
			FileOutputStream output = new FileOutputStream(targetFile);
			BufferedOutputStream outBuff = new BufferedOutputStream(output);

			// 缓冲数组
			byte[] b = new byte[1024 * 5];
			int len;
			while ((len = inBuff.read(b)) != -1) {
				outBuff.write(b, 0, len);
			}
			// 刷新此缓冲的输出流
			outBuff.flush();

			// 关闭流
			inBuff.close();
			outBuff.close();
			output.close();
			input.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public static int getMyEleCounts(String path) {
		File file = new File(path);
		if (file.isDirectory()) {
			return file.list().length;
		}
		return 0;

	}

	public static List<PicFileBean> getImageNames(String folderPath) {
		List<PicFileBean> pictureFiles = new ArrayList<PicFileBean>();
		File file = new File(folderPath);
		if (file.isDirectory()) {
			String[] filelist = file.list();
			for (int i = 0; i < filelist.length; i++) {
				File file02 = new File(folderPath + "/" + filelist[i]);

				if (!file02.isDirectory()) {
					// if (isImageFile(file02.getName())) {
					PicFileBean pictureFile = new PicFileBean(filelist[i],
							file02.getAbsolutePath());
					pictureFiles.add(pictureFile);
					// }
				}
			}

		}
		return pictureFiles;

	}

	private static boolean isImageFile(String fileName) {
		String fileEnd = fileName.substring(fileName.lastIndexOf(".") + 1,
				fileName.length());
		if (fileEnd.equalsIgnoreCase("jpg")) {
			return true;
		} else if (fileEnd.equalsIgnoreCase("png")) {
			return true;
		} else if (fileEnd.equalsIgnoreCase("bmp")) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 复制asset文件夹下的文件到sd卡上
	 * 
	 * @param context
	 *            上下文
	 * @param assetDir
	 *            asset指定文件夹的路径
	 * @param dir
	 *            sd卡指定文件夹的路径
	 */
	public static void copyAssets(Context context, String assetDir, String dir) {
		String[] files;
		try {
			files = context.getResources().getAssets().list(assetDir);
		} catch (IOException e1) {
			return;
		}
		File mWorkingPath = new File(dir);
		// if this directory does not exists, make one.
		if (!mWorkingPath.exists()) {
			if (!mWorkingPath.mkdirs()) {

			}
		}
		for (int i = 0; i < files.length; i++) {
			try {
				String fileName = files[i];
				// we make sure file name not contains '.' to be a folder.
				if (!fileName.contains(".")) {
					if (0 == assetDir.length()) {
						// 这里使用的递归
						copyAssets(context, fileName, dir + fileName + "/");
					} else {
						copyAssets(context, assetDir + "/" + fileName, dir
								+ fileName + "/");
					}
					continue;
				}
				File outFile = new File(mWorkingPath, fileName);
				if (outFile.exists()) {
					continue;
				}
				InputStream in = null;
				if (0 != assetDir.length()) {
					in = context.getAssets().open(assetDir + "/" + fileName);
				} else {
					in = context.getAssets().open(fileName);
				}
				OutputStream out = new FileOutputStream(outFile);

				// Transfer bytes from in to out
				byte[] buf = new byte[1024];
				int len;
				while ((len = in.read(buf)) > 0) {
					out.write(buf, 0, len);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	public static boolean existFile(String path) {
		File file = new File(path);
		if (file.exists()) {
			return true;
		} else {
			return false;
		}

	}

	public static void createFolder(String path) {
		File file = new File(path);
		if (!file.exists()) {
			file.mkdirs();
		}

	}

	/**
	 * 删除文件夹
	 * 
	 * @param folderPath
	 */
	public static void delFolder(String folderPath) {
		try {
			delAllFile(folderPath); // 删除完里面所有内容
			String filePath = folderPath;
			filePath = filePath.toString();
			java.io.File myFilePath = new java.io.File(filePath);
			myFilePath.delete(); // 删除空文件夹

		} catch (Exception e) {
			System.out.println("删除文件夹操作出错");
			e.printStackTrace();

		}
	}

	public static void delAllFile(String path) {
		File file = new File(path);
		if (!file.exists()) {
			return;
		}
		if (!file.isDirectory()) {
			return;
		}
		String[] tempList = file.list();
		File temp = null;
		for (int i = 0; i < tempList.length; i++) {
			if (path.endsWith(File.separator)) {
				temp = new File(path + tempList[i]);
			} else {
				temp = new File(path + File.separator + tempList[i]);
			}
			if (temp.isFile()) {
				temp.delete();
			}
			if (temp.isDirectory()) {
				delAllFile(path + "/" + tempList[i]);// 先删除文件夹里面的文件
				delFolder(path + "/" + tempList[i]);// 再删除空文件夹
			}
		}
	}

}


package com.su.filesystem;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


import android.util.Log;

public class FileUtil {
	public int j = 0;
	public static ArrayList<File> list = new ArrayList<File>();

	// 根据路径path获取该路径下的所有文件的文件名
	public String[] getFileNames(String path) {
		File file = new File(path);
		return file.list();
	}

	public void renameFile(String oldFile, String newFile) {
		File file = new File(oldFile);
		file.renameTo(new File(newFile));
	}
	public void createFolder(String sfile) {
		File file = new File(sfile);
		file.mkdirs();
	}
	public void createFile(String sfile) throws IOException {
		File file = new File(sfile);
		file.createNewFile();
	}

	// 根据文件后缀名判断是不是txt文件
	public boolean isTxtFile(String fileName) {
		File file = new File(fileName);
		String fileEnd = fileName.substring(fileName.lastIndexOf(".") + 1,
				fileName.length());
		if (fileEnd.equalsIgnoreCase("txt")) {
			return true;
		} else {
			return false;
		}
	}

	public boolean isMp3File(String fileName) {
		String fileEnd = fileName.substring(fileName.lastIndexOf(".") + 1,
				fileName.length());
		if (fileEnd.equalsIgnoreCase("mp3")) {
			return true;

		} else {
			return false;
		}
	}
	public boolean isImageFile(String fileName) {
		String fileEnd = fileName.substring(fileName.lastIndexOf(".") + 1,
				fileName.length());
		if (fileEnd.equalsIgnoreCase("jpg")) {
			return true;

		} else if (fileEnd.equalsIgnoreCase("png")) {
			return true;
			
		}
		else if (fileEnd.equalsIgnoreCase("gif")) {
			return true;
		}
		else
		{
			return false;
		}
	}

	// 判断是什么格式的文件
	public int isWhichFile(String fileName) {
		String fileEnd = fileName.substring(fileName.lastIndexOf(".") + 1,
				fileName.length());
		if (fileEnd.equalsIgnoreCase("txt")) {
			return R.drawable.file_txt;
		} else if (fileEnd.equalsIgnoreCase("lrc")) {
			return R.drawable.file_lrc;
		} else {
			return R.drawable.file_unknown;
		}
	}

	public void copyFolder(String oldPath, String newPath) {

		try {
			(new File(newPath)).mkdirs();
			// 如果文件夹不存在 则建立新文件夹
			File a = new File(oldPath);
			String[] file = a.list();
			File temp = null;
			for (int i = 0; i < file.length; i++) {
				if (oldPath.endsWith(File.separator)) {
					temp = new File(oldPath + file[i]);
				} else {
					temp = new File(oldPath + File.separator + file[i]);
				}
				if (temp.isFile()) {
					FileInputStream input = new FileInputStream(temp);
					FileOutputStream output = new FileOutputStream(newPath
							+ "/" + (temp.getName()).toString());
					byte[] b = new byte[1024 * 5];
					int len;
					while ((len = input.read(b)) != -1) {
						output.write(b, 0, len);
					}
					output.flush();
					output.close();
					input.close();
				}
				if (temp.isDirectory() && !newPath.contains(oldPath)) {// 如果是子文件夹
																		// 还要判断是否是复制在本目录下如果复制本目录下
																		// 那只递归一次否则死循环
					copyFolder(oldPath + "/" + file[i], newPath + "/" + file[i]);
				}
			}
		} catch (Exception e) {
			System.out.println("复制整个文件夹内容操作出错");
			e.printStackTrace();
		}
	}

	public boolean copyFile(String frompath, String topath) {
		try {
			File fromFile = new File(frompath);
			File toFile = new File(topath);
			FileInputStream fosfrom = new FileInputStream(fromFile);
			FileOutputStream fosto = new FileOutputStream(toFile);
			byte bt[] = new byte[1024];
			int c;
			while ((c = fosfrom.read(bt)) > 0) {
				fosto.write(bt, 0, c); // 将内容写到新文件当中
			}
			fosfrom.close();
			fosto.close();
		} catch (Exception ex) {
			Log.e("readfile", ex.getMessage());
		}
		return true;
	}

	public boolean delFile(String path) {
		File file = new File(path);
		return file.delete();
		// return true;
	}

	public void delFolder(String folderPath) {
		try {
			delAllFile(folderPath); // 删除完里面所有内容
			String filePath = folderPath;
			filePath = filePath.toString();
			java.io.File myFilePath = new java.io.File(filePath);
			myFilePath.delete(); // 删除空文件夹

		} catch (Exception e) {
			System.out.println("删除文件夹操作出错");
			e.printStackTrace();

		}
	}

	/**
	 * 删除文件夹里面的所有文件
	 * 
	 * @param path
	 * 
	 */
	public void delAllFile(String path) {
		File file = new File(path);
		if (!file.exists()) {
			return;
		}
		if (!file.isDirectory()) {
			return;
		}
		String[] tempList = file.list();
		File temp = null;
		for (int i = 0; i < tempList.length; i++) {
			if (path.endsWith(File.separator)) {
				temp = new File(path + tempList[i]);
			} else {
				temp = new File(path + File.separator + tempList[i]);
			}
			if (temp.isFile()) {
				temp.delete();
			}
			if (temp.isDirectory()) {
				delAllFile(path + "/" + tempList[i]);// 先删除文件夹里面的文件
				delFolder(path + "/" + tempList[i]);// 再删除空文件夹
			}
		}
	}

	public static ArrayList<File> getAllFiles(File root) {

		File files[] = root.listFiles();

		if (files != null)
			for (File f : files) {

				if (f.isDirectory()) {
					getAllFiles(f);
				} else {
					if (f.getName().indexOf(".lrc") > 0)
						list.add(f);
				}
			}
		return list;
	}
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值