Java操作文件

来源:互联网 发布:mac lnmp一键安装包 编辑:程序博客网 时间:2024/06/07 10:03

java文件操作

import java.io.BufferedReader;import java.io.ByteArrayOutputStream;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.FileReader;import java.io.FileWriter;import java.io.IOException;import java.io.InputStream;import java.io.PrintWriter;import java.math.BigInteger;import java.nio.ByteBuffer;import java.nio.MappedByteBuffer;import java.nio.channels.FileChannel;import java.security.MessageDigest;import java.text.DecimalFormat;import java.util.Arrays;import java.util.Enumeration;import java.util.HashSet;import java.util.List;import java.util.Set;import org.apache.tools.ant.Project;import org.apache.tools.ant.taskdefs.Zip;import org.apache.tools.ant.types.FileSet;import org.apache.tools.zip.ZipEntry;import org.apache.tools.zip.ZipFile;/** * @author 王泽浩 *  *         E-mail: 1028625100@qq.com *  * @version v1.1 *  *          创建时间:2014年3月12日 下午2:17:45 *           *          操作文件的工具类 */public class FileUtil {private FileUtil(){}/** * 获取文件MD5值 *  * @param file * @return */public static String getMd5ByFile(File file) {String value = null;FileInputStream in = null;try {in = new FileInputStream(file);MappedByteBuffer byteBuffer = in.getChannel().map(FileChannel.MapMode.READ_ONLY, 0, file.length());MessageDigest md5 = MessageDigest.getInstance("MD5");md5.update(byteBuffer);BigInteger bi = new BigInteger(1, md5.digest());value = bi.toString(16).toUpperCase();} catch (Exception e) {e.printStackTrace();} finally {close(in);}return value;}/** * 获取文件大小 *  * @param file * @return */public static long getFileLength(File file) {try {return new FileInputStream(file).available();} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}return -1l;}/** * 读取文件到二进制 *  * @param file * @return * @throws IOException */public static byte[] getBytesFromFile(File file) throws IOException {InputStream is = new FileInputStream(file);long length = file.length();if (length > Integer.MAX_VALUE) {// File is too large}byte[] bytes = new byte[(int) length];// Read in the bytesint offset = 0;int numRead = 0;while (offset < bytes.length && (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) {offset += numRead;}close(is);return bytes;}/** * 获取标准文件大小,如30KB,15.5MB *  * @param file * @return * @throws IOException */public static String getFileSize(File file) {long size = getFileLength(file);DecimalFormat df = new DecimalFormat("###.##");float f;if (size < 1024 * 1024) {f = (float) ((float) size / (float) 1024);return (df.format(new Float(f).doubleValue()) + " KB");} else {f = (float) ((float) size / (float) (1024 * 1024));return (df.format(new Float(f).doubleValue()) + " MB");}}/** * 复制文件 *  * @param f1 *            源文件 *  * @param f2 *            目标文件 *  * @return true复制成功,false复制失败 */public static boolean copyFile(File f1, File f2) {FileInputStream in = null;FileOutputStream out = null;FileChannel inC = null;FileChannel outC = null;try {int length = 2097152;in = new FileInputStream(f1);out = new FileOutputStream(f2);inC = in.getChannel();outC = out.getChannel();ByteBuffer b = null;while (true) {if (inC.position() == inC.size()) {close(in, out,inC, outC);}if ((inC.size() - inC.position()) < length) {length = (int) (inC.size() - inC.position());} elselength = 2097152;b = ByteBuffer.allocateDirect(length);inC.read(b);b.flip();outC.write(b);outC.force(false);return true;}} catch (Exception e) {e.printStackTrace();return false;} finally {close(in, out,inC, outC);}}/** * 检查文件是否存在 *  * @param fileName *  * @return 返回true则是有该文件 false则是没有该文件 */public static boolean existFile(String fileName) {try {File file = new File(fileName);if (!file.exists()) {return false;}return file.exists();} catch (Exception e) {e.printStackTrace();return false;}}/** * 删除文件 *  * @param fileName */public static boolean deleteFile(String fileName) {File file = new File(fileName);try {if (!file.exists()) {return false;}file.delete();return true;} catch (Exception e) {e.printStackTrace();return false;} finally {file = null;}}/** * 读取文件到字符串 *  * @param fileName *  * @return */public static String readFile(String fileName) {try {File file = new File(fileName);if (!file.exists()) {return null;}BufferedReader in = new BufferedReader(new FileReader(file));StringBuffer sb = new StringBuffer();String str = "";while ((str = in.readLine()) != null) {sb.append(str);}close(in);return sb.toString();} catch (Exception e) {e.printStackTrace();return null;}}/** * 获取目录所有所有文件和文件夹 *  * @param fileName *  * @return */public static List<File> listFiles(String fileName) {File file = new File(fileName);if (!file.exists()) {return null;}return Arrays.asList(file.listFiles());}/** * 创建目录 *  * @param dir */public static void mkdir(String dir) {File dirPath = new File(dir);if (!dirPath.exists()) {dirPath.mkdir();}}/** * 新建文件 *  * @param fileName *            String 包含路径的文件名 如:E:\123.txt * @param content *            String 文件内容 */public static void createNewFile(String fileName, String content){FileWriter fw = null;PrintWriter pw = null;try {String fileNameTemp = fileName;File filePath = new File(fileNameTemp);if (!filePath.exists()) {filePath.createNewFile();}fw = new FileWriter(filePath);pw = new PrintWriter(fw);String strContent = content;pw.println(strContent);pw.flush();} catch (Exception e) {e.printStackTrace();}finally{close(pw,fw);}}/** * 删除文件夹 *  * @param folderPath *            文件夹路径 */public static void delFolder(String folderPath) {// 删除文件夹里面所有内容delAllFile(folderPath);String filePath = folderPath;File myFilePath = new File(filePath);// 删除空文件夹myFilePath.delete();}/** * 删除文件夹里面的所有文件 *  * @param path *            文件夹路径 */public static void delAllFile(String path) {File file = new File(path);if (!file.exists()) {return;}if (!file.isDirectory()) {return;}String[] childFiles = file.list();File temp = null;for (int i = 0; i < childFiles.length; i++) {// File.separator与系统有关的默认名称分隔符// 在UNIX系统上,此字段的值为'/';在Microsoft Windows系统上,它为 '\'。if (path.endsWith(File.separator)) {temp = new File(path + childFiles[i]);} else {temp = new File(path + File.separator + childFiles[i]);}if (temp.isFile()) {temp.delete();}if (temp.isDirectory()) {delAllFile(path + File.separatorChar + childFiles[i]);// 先删除文件夹里面的文件delFolder(path + File.separatorChar + childFiles[i]);// 再删除空文件夹}}}/** * 复制单个文件,传统方式 *  * @param srcFile *            包含路径的源文件 如:E:/abc.txt * @param dirDest *            目标文件目录;若文件目录不存在则自动创建 如:E:/dest */public static void copyFile(String srcFile, String dirDest){FileInputStream in = null;FileOutputStream out = null;try {in = new FileInputStream(srcFile);mkdir(dirDest);out = new FileOutputStream(dirDest + "/"+ new File(srcFile).getName());int len;byte buffer[] = new byte[1024];while ((len = in.read(buffer)) != -1) {out.write(buffer, 0, len);}out.flush();} catch (Exception e) {e.printStackTrace();} finally {close(in, out);}}/** * 复制单个文件,传统方式 *  * @param srcFile *            包含路径的源文件 如:E://abc.txt * @param dirDest *            目标文件目录;若文件目录不存在则自动创建 如:E:/dest * @param fileName *            目标文件名称 * @throws IOException */public static void copyFile(File srcFile, String dirDest, String fileName) {FileInputStream in = null;FileOutputStream out = null;try {in = new FileInputStream(srcFile);mkdir(dirDest);out = new FileOutputStream(dirDest + "/" + fileName);int len;byte buffer[] = new byte[1024];while ((len = in.read(buffer)) != -1) {out.write(buffer, 0, len);}out.flush();} catch (Exception e) {e.printStackTrace();} finally {close(in, out);}}/** * 复制文件夹 *  * @param oldPath *            String 源文件夹路径 如:E:/src *             * @param newPath *            String 目标文件夹路径 如:E:/dest *             * @return boolean 返回true时复制成功,false择复制失败 */public static boolean copyFolder(String oldPath, String newPath){FileInputStream in = null;FileOutputStream out = null;try {// 如果文件夹不存在 则新建文件夹mkdir(newPath);File file = new File(oldPath);String[] files = file.list();File temp = null;for (int i = 0; i < files.length; i++) {if (oldPath.endsWith(File.separator)) {temp = new File(oldPath + files[i]);} else {temp = new File(oldPath + File.separator + files[i]);}if (temp.isFile()) {in = new FileInputStream(temp);out = new FileOutputStream(newPath + "/"+ (temp.getName()).toString());byte[] buffer = new byte[1024 * 2];int len;while ((len = in.read(buffer)) != -1) {out.write(buffer, 0, len);}out.flush();}// 如果是子文件夹if (temp.isDirectory()) {copyFolder(oldPath + "/" + files[i], newPath + "/" + files[i]);}}return true;} catch (Exception e) {e.printStackTrace();return false;} finally {close(in, out);}}/** * 移动文件到指定目录 *  * @param oldPath *            包含路径的文件名 如:E:/src/ljq.txt *             * @param newPath *            目标文件目录 如:E:/dest * *@return boolean 返回true时移动成功,false择移动失败 */public static boolean moveFile(String oldPath, String newPath){try {copyFile(oldPath, newPath);deleteFile(oldPath);return true;} catch (Exception e) {e.printStackTrace();return false;}}/** * 移动文件到指定目录,不会删除文件夹 *  * @param oldPath *            源文件目录 如:E:/src *             * @param newPath *            目标文件目录 如:E:/dest *  * @return boolean 返回true时移动成功,false择移动失败 */public static boolean moveFiles(String oldPath, String newPath){try {copyFolder(oldPath, newPath);delAllFile(oldPath);return true;} catch (Exception e) {e.printStackTrace();return false;}}/** * 移动文件到指定目录,会删除文件夹 *  * @param oldPath *            源文件目录 如:E:/src *             * @param newPath *            目标文件目录 如:E:/dest *             *@return boolean 返回true时移动成功,false择移动失败             */public static boolean moveFolder(String oldPath, String newPath){try {copyFolder(oldPath, newPath);delFolder(oldPath);return true;} catch (Exception e) {e.printStackTrace();return false;}}/** *解压zip * * @param path *            解压到的目录 *             * @param zipFile *  *            压缩文件 *  * @return boolean 返回true时解压成功,false择解压失败 */public static boolean unZip(String path, ZipFile zipFile) {FileOutputStream fileOutputStream = null;InputStream inputStream = null;File file = null;try {int bufSize = 512;byte[] buf = new byte[bufSize];int readedBytes;for (Enumeration<ZipEntry> entries = zipFile.getEntries(); entries.hasMoreElements();) {ZipEntry entry = entries.nextElement();file = new File(path + "/" + entry.getName());if (entry.isDirectory()) {file.mkdirs();} else {File parent = file.getParentFile();if (!parent.exists()) {parent.mkdirs();}inputStream = zipFile.getInputStream(entry);fileOutputStream = new FileOutputStream(file);while ((readedBytes = inputStream.read(buf)) > 0) {fileOutputStream.write(buf, 0, readedBytes);}close(fileOutputStream, inputStream);}}zipFile.close();return true;} catch (Exception e) {e.printStackTrace();return false;} finally {close(fileOutputStream, inputStream);}}/** * 压缩文件 * @param src *  * @param dest *  * @return boolean 返回true时压缩成功,false择压缩失败 */public static boolean zip(File src, File dest){try {Project prj = new Project();Zip zip = new Zip();zip.setProject(prj);zip.setDestFile(dest);FileSet fileSet = new FileSet();fileSet.setProject(prj);if (src.isFile()) {fileSet.setFile(src);} else {fileSet.setDir(src);}zip.addFileset(fileSet);zip.execute();return true;} catch (Exception e) {e.printStackTrace();return false;}}/** * 读取数据 *  * @param inSream * @param charsetName * @return */public static String readData(InputStream inSream, String charsetName){ByteArrayOutputStream outStream = null;try {outStream = new ByteArrayOutputStream();byte[] buffer = new byte[1024];int len = -1;while ((len = inSream.read(buffer)) != -1) {outStream.write(buffer, 0, len);}byte[] data = outStream.toByteArray();return new String(data, charsetName);} catch (Exception e) {e.printStackTrace();return null;} finally {close(inSream,outStream);}}/** * 一行一行读取文件,适合字符读取,若读取中文字符时会出现乱码 *  * @param path * @return * @throws Exception */public static Set<String> readFileLine(String path){FileReader fr = null;BufferedReader br = null;try {Set<String> datas = new HashSet<String>();fr = new FileReader(path);br = new BufferedReader(fr);String line = null;while ((line = br.readLine()) != null) {datas.add(line);}return datas;} catch (Exception e) {e.printStackTrace();return null;} finally {close(fr,br);}}public static void close(AutoCloseable... autoCloseables) {try {if (autoCloseables != null) {for (AutoCloseable autoCloseable : autoCloseables) {autoCloseable.close();}}} catch (Exception e) {e.printStackTrace();}}}


0 0
原创粉丝点击