java删除文件:文件操作FileUtil.java的方法来源: 发布时间:星期四, 2009年2月12日 浏览:1092次 评论:0
package com.work.util; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.RandomAccessFile; import java.io.StringReader; import java.util.ArrayList; import java.util.List; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * 日 期: 2008-2-14 12:05:18<br /> * project: zxj <br /> * 作 者:wangmingjie<br /> */ public FileUtil { private Log log = LogFactory.getLog(FileUtil.); /** * 创建单个文件夹 * * @param dir * @param ignoreIfExitst * true 表示如果文件夹存在就不再创建了false是重新创建 * @throws IOException */ public void createDir(String dir, boolean ignoreIfExitst) throws IOException { File file = File(dir); (ignoreIfExitst && file.exists) { ; } (file.mkdir false) { throw IOException("Cannot create the directory = " + dir); } } /** * 创建多个文件夹 * * @param dir * @param ignoreIfExitst * @throws IOException */ public void createDirs(String dir, boolean ignoreIfExitst) throws IOException { File file = File(dir); (ignoreIfExitst && file.exists) { ; } (file.mkdirs false) { throw IOException("Cannot create directories = " + dir); } } /** * 删除个文件 * * @param filename * @throws IOException */ public void deleteFile(String filename) throws IOException { File file = File(filename); log.trace("Delete file = " + filename); (file.isDirectory) { throw IOException( "IOException -> BadInputException: not a file."); } (file.exists false) { throw IOException( "IOException -> BadInputException: file is not exist."); } (file.delete false) { throw IOException("Cannot delete file. filename = " + filename); } } /** * 删除文件夹及其下面子文件夹 * * @param dir * @throws IOException */ public void deleteDir(File dir) throws IOException { (dir.isFile) throw IOException( "IOException -> BadInputException: not a directory."); File files = dir.listFiles; (files != null) { for ( i = 0; i < files.length; i) { File file = files[i]; (file.isFile) { file.delete; } { deleteDir(file); } } }// dir.delete; } public String getPathSeparator { java.io.File.pathSeparator; } public String getFileSeparator { java.io.File.separator; } /** * 列出指定文件目录下面文件信息 * * @param dir * @ * @throws IOException */ public List<FileInfo> getFiles(File dir) throws IOException { (dir.isFile) throw IOException("BadInputException: not a directory."); (!dir.exists) { throw IOException(" don't exist "); } File files = dir.listFiles; LEN = 0; (files != null) { LEN = files.length; } List<FileInfo> l = ArrayList<FileInfo>; long tempFLen = 0; //文件长度 for ( i = 0; i < LEN; i) { FileInfo temp = FileInfo; temp.FileName(files[i].getName); temp.IsDir(files[i].isDirectory); //是文件且包含. (files[i].isFile) { (files[i].getName.lastIndexOf(".")!=-1) temp.FileType(files[i].getName.sub( files[i].getName.lastIndexOf("."))); }{ temp.FileType("文件夹"); } tempFLen = files[i].length; temp.FileLen(tempFLen); (tempFLen/1024/1024/1024 >0){ temp.FileLength(files[i].length / 1024/1024/1024 + "G"); } (tempFLen/1024/1024 >0){ temp.FileLength(files[i].length / 1024/1024 + "M"); } (tempFLen/1024 >0){ temp.FileLength(files[i].length / 1024 + "K"); }{ temp.FileLength(tempFLen+""); } temp.FilePath(files[i].getAbsolutePath.replaceAll("[\\\\]", "/")); temp.LastModiedTime(com.work.util.DateUtil .getDateTime(files[i].lastModied)); temp.IsHidden(files[i].isHidden); temp.Author(null); temp.Version(null); temp.FileClass(null); temp.Remark(null); l.add(temp); } l; } /** * 获取到目录下面文件大小包含了子目录 * * @param dir * @ * @throws IOException */ public long getDirLength(File dir) throws IOException { (dir.isFile) throw IOException("BadInputException: not a directory."); long size = 0; File files = dir.listFiles; (files != null) { for ( i = 0; i < files.length; i) { File file = files[i]; // file.getName; // .out.prln(file.getName); long length = 0; (file.isFile) { length = file.length; } { length = getDirLength(file); } size length; }// for }// size; } /** * 将文件清空 * * @param srcFilename * @throws IOException */ public void emptyFile(String srcFilename) throws IOException { File srcFile = File(srcFilename); (!srcFile.exists) { throw FileNotFoundException("Cannot find the file: " + srcFile.getAbsolutePath); } (!srcFile.canWrite) { throw IOException("Cannot write the file: " + srcFile.getAbsolutePath); } FileOutputStream outputStream = FileOutputStream(srcFilename); outputStream.close; } /** * Write content to a fileName with the destEncoding 写文件如果此文件不存在就创建个 * * @param content * String * @param fileName * String * @param destEncoding * String * @throws FileNotFoundException * @throws IOException */ public void writeFile(String content, String fileName, String destEncoding) throws FileNotFoundException, IOException { File file = null; try { file = File(fileName); (!file.exists) { (file.createNewFile false) { throw IOException("create file '" + fileName + "' failure."); } } (file.isFile false) { throw IOException("'" + fileName + "' is not a file."); } (file.canWrite false) { throw IOException("'" + fileName + "' is a read-only file."); } } finally { // we dont have to close File here } BufferedWriter out = null; try { FileOutputStream fos = FileOutputStream(fileName); out = BufferedWriter( OutputStreamWriter(fos, destEncoding)); out.write(content); out.flush; } catch (FileNotFoundException fe) { log.error("Error", fe); throw fe; } catch (IOException e) { log.error("Error", e); throw e; } finally { try { (out != null) out.close; } catch (IOException ex) { } } } /** * 读取文件内容并将文件内容以串形式返回 * * @param fileName * @param srcEncoding * @ * @throws FileNotFoundException * @throws IOException */ public String readFile(String fileName, String srcEncoding) throws FileNotFoundException, IOException { File file = null; try { file = File(fileName); (file.isFile false) { throw IOException("'" + fileName + "' is not a file."); } } finally { // we dont have to close File here } BufferedReader reader = null; try { StringBuffer result = StringBuffer(1024); FileInputStream fis = FileInputStream(fileName); reader = BufferedReader( InputStreamReader(fis, srcEncoding)); char block = char[512]; while (true) { readLength = reader.read(block); (readLength -1) ;// end of file result.append(block, 0, readLength); } result.toString; } catch (FileNotFoundException fe) { log.error("Error", fe); throw fe; } catch (IOException e) { log.error("Error", e); throw e; } finally { try { (reader != null) reader.close; } catch (IOException ex) { } } } /* * 1 ABC 2 abC Gia su doc tu dong 1 lay ca thay 5 dong => 1 --> 5 3 ABC */ public String getLastLines(File file, linesToReturn) throws IOException, FileNotFoundException { final AVERAGE_CHARS_PER_LINE = 250; final BYTES_PER_CHAR = 2; RandomAccessFile randomAccessFile = null; StringBuffer buffer = StringBuffer(linesToReturn * AVERAGE_CHARS_PER_LINE); lineTotal = 0; try { randomAccessFile = RandomAccessFile(file, "r"); long Total = randomAccessFile.length; long EstimateToRead = linesToReturn * AVERAGE_CHARS_PER_LINE * BYTES_PER_CHAR; long off = Total - EstimateToRead; (off < 0) { off = 0; } randomAccessFile.seek(off); // log.debug("SKIP IS ::" + off); String line = null; String lineUTF8 = null; while ((line = randomAccessFile.readLine) != null) { lineUTF8 = String(line.getBytes("ISO8859_1"), "UTF-8"); lineTotal; buffer.append(lineUTF8).append("\n"); } } finally { (randomAccessFile != null) { try { randomAccessFile.close; } catch (IOException ex) { } } } String resultLines = String[linesToReturn]; BufferedReader in = null; try { in = BufferedReader( StringReader(buffer.toString)); start = lineTotal /* + 2 */- linesToReturn; // Ex : 55 - 10 = 45 // ~ off (start < 0) start = 0; // not start line for ( i = 0; i < start; i) { in.readLine; // loop until the off. Ex: loop 0, 1 ~~ 2 // lines } i = 0; String line = null; while ((line = in.readLine) != null) { resultLines[i] = line; i; } } catch (IOException ie) { log.error("Error" + ie); throw ie; } finally { (in != null) { try { in.close; } catch (IOException ex) { } } } resultLines; } /** * 单个文件拷贝 * * @param srcFilename * @param destFilename * @param overwrite * @throws IOException */ public void copyFile(String srcFilename, String destFilename, boolean overwrite) throws IOException { File srcFile = File(srcFilename); // 首先判断源文件是否存在 (!srcFile.exists) { throw FileNotFoundException("Cannot find the source file: " + srcFile.getAbsolutePath); } // 判断源文件是否可读 (!srcFile.canRead) { throw IOException("Cannot read the source file: " + srcFile.getAbsolutePath); } File destFile = File(destFilename); (overwrite false) { // 目标文件存在就不覆盖 (destFile.exists) ; } { // 如果要覆盖已经存在目标文件首先判断是否目标文件可写 (destFile.exists) { (!destFile.canWrite) { throw IOException("Cannot write the destination file: " + destFile.getAbsolutePath); } } { // 不存在就创建个新空文件 (!destFile.createNewFile) { throw IOException("Cannot write the destination file: " + destFile.getAbsolutePath); } } } BufferedInputStream inputStream = null; BufferedOutputStream outputStream = null; block = [1024]; try { inputStream = BufferedInputStream( FileInputStream(srcFile)); outputStream = BufferedOutputStream( FileOutputStream( destFile)); while (true) { readLength = inputStream.read(block); (readLength -1) ;// end of file outputStream.write(block, 0, readLength); } } finally { (inputStream != null) { try { inputStream.close; } catch (IOException ex) { // just ignore } } (outputStream != null) { try { outputStream.close; } catch (IOException ex) { // just ignore } } } } /** * 单个文件拷贝 * * @param srcFile * @param destFile * @param overwrite * 是否覆盖目文件 * @throws IOException */ public void copyFile(File srcFile, File destFile, boolean overwrite) throws IOException { // 首先判断源文件是否存在 (!srcFile.exists) { throw FileNotFoundException("Cannot find the source file: " + srcFile.getAbsolutePath); } // 判断源文件是否可读 (!srcFile.canRead) { throw IOException("Cannot read the source file: " + srcFile.getAbsolutePath); } (overwrite false) { // 目标文件存在就不覆盖 (destFile.exists) ; } { // 如果要覆盖已经存在目标文件首先判断是否目标文件可写 (destFile.exists) { (!destFile.canWrite) { throw IOException("Cannot write the destination file: " + destFile.getAbsolutePath); } } { // 不存在就创建个新空文件 (!destFile.createNewFile) { throw IOException("Cannot write the destination file: " + destFile.getAbsolutePath); } } } BufferedInputStream inputStream = null; BufferedOutputStream outputStream = null; block = [1024]; try { inputStream = BufferedInputStream( FileInputStream(srcFile)); outputStream = BufferedOutputStream( FileOutputStream( destFile)); while (true) { readLength = inputStream.read(block); (readLength -1) ;// end of file outputStream.write(block, 0, readLength); } } finally { (inputStream != null) { try { inputStream.close; } catch (IOException ex) { // just ignore } } (outputStream != null) { try { outputStream.close; } catch (IOException ex) { // just ignore } } } } /** * 拷贝文件从源文件夹拷贝文件到目文件夹 <br> * 参数源文件夹和目文件夹最后都不要带文件路径符号例如:c:/aa正确c:/aa/ * * @param srcDirName * 源文件夹名称 ,例如:c:/test/aa 或者c:\\test\\aa * @param destDirName * 目文件夹名称,例如:c:/test/aa 或者c:\\test\\aa * @param overwrite * 是否覆盖目文件夹下面文件 * @throws IOException */ public void copyFiles(String srcDirName, String destDirName, boolean overwrite) throws IOException { File srcDir = File(srcDirName);// 声明源文件夹 // 首先判断源文件夹是否存在 (!srcDir.exists) { throw FileNotFoundException( "Cannot find the source directory: " + srcDir.getAbsolutePath); } File destDir = File(destDirName); (overwrite false) { (destDir.exists) { // do nothing } { (destDir.mkdirs false) { throw IOException( "Cannot create the destination directories = " + destDir); } } } { // 覆盖存在目文件夹 (destDir.exists) { // do nothing } { // create a directory (destDir.mkdirs false) { throw IOException( "Cannot create the destination directories = " + destDir); } } } // 循环查找源文件夹目录下面文件(屏蔽子文件夹)然后将其拷贝到指定目文件夹下面 File srcFiles = srcDir.listFiles; (srcFiles null || srcFiles.length < 1) { // throw IOException ("Cannot find any file from source // directory!!!"); ;// do nothing } // 开始复制文件 SRCLEN = srcFiles.length; for ( i = 0; i < SRCLEN; i) { // File tempSrcFile = srcFiles[i]; File destFile = File(destDirName + File.separator + srcFiles[i].getName); // 注意构造文件对象时候文件名串中不能包含文件路径分隔符";". // log.debug(destFile); (srcFiles[i].isFile) { copyFile(srcFiles[i], destFile, overwrite); } { // 在这里进行递归就可以实现子文件夹拷贝 copyFiles(srcFiles[i].getAbsolutePath, destDirName + File.separator + srcFiles[i].getName, overwrite); } } } /** * 压缩文件注意:中文文件名称和中文评论会乱码 * @param srcFilename * @param destFilename * @param overwrite * @throws IOException */ public void zipFile(String srcFilename, String destFilename, boolean overwrite) throws IOException { File srcFile = File(srcFilename); // 首先判断源文件是否存在 (!srcFile.exists) { throw FileNotFoundException("Cannot find the source file: " + srcFile.getAbsolutePath); } // 判断源文件是否可读 (!srcFile.canRead) { throw IOException("Cannot read the source file: " + srcFile.getAbsolutePath); } (destFilenamenull || destFilename.trim.equals("")){ destFilename = srcFilename+".zip"; }{ destFilename ".zip"; } File destFile = File(destFilename); (overwrite false) { // 目标文件存在就不覆盖 (destFile.exists) ; } { // 如果要覆盖已经存在目标文件首先判断是否目标文件可写 (destFile.exists) { (!destFile.canWrite) { throw IOException("Cannot write the destination file: " + destFile.getAbsolutePath); } } { // 不存在就创建个新空文件 (!destFile.createNewFile) { throw IOException("Cannot write the destination file: " + destFile.getAbsolutePath); } } } BufferedInputStream inputStream = null; BufferedOutputStream outputStream = null; ZipOutputStream zipOutputStream = null; block = [1024]; try { inputStream = BufferedInputStream( FileInputStream(srcFile)); outputStream = BufferedOutputStream( FileOutputStream(destFile)); zipOutputStream = ZipOutputStream(outputStream); zipOutputStream.Comment("通过java压缩"); ZipEntry zipEntry = ZipEntry(srcFile.getName); zipEntry.Comment(" zipEntry通过java压缩"); zipOutputStream.putNextEntry(zipEntry); while (true) { readLength = inputStream.read(block); (readLength -1) ;// end of file zipOutputStream.write(block, 0, readLength); } zipOutputStream.flush; zipOutputStream.finish; } finally { (inputStream != null) { try { inputStream.close; } catch (IOException ex) { // just ignore } } (outputStream != null) { try { outputStream.close; } catch (IOException ex) { // just ignore } } (zipOutputStream != null) { try { zipOutputStream.close; } catch (IOException ex) { // just ignore } } } } /** * @param args * @throws IOException */ public void (String args) throws IOException { FileUtil.createDirs("d:/logs/aaaaaaaa/spring.log", false); FileUtil.zipFile("d:/logs/复件 work.log", null, true); .out.prln(getFileSeparator); String temp = FileUtil.getLastLines( File("d:/logs/work.log"), 5); for ( i = 0; i < temp.length; i) { .out.prln(temp[i]); } } } 4
相关文章读者评论发表评论 |