`

FileUtil(File处理工具类,copy,压缩,删除等)

阅读更多

File处理工具

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.text.DateFormat;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;
import java.util.Locale;
import java.util.StringTokenizer;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

/**
 * 
 * @author IBM
 * 
 */

public class FileUtil {
	
	public static String dirSplit = "\\";//linux windows
	/**
	 * save file accroding to physical directory infomation
	 * 
	 * @param physicalDir
	 *            physical directory
	 * @param fname
	 *            file name of destination
	 * @param istream
	 *            input stream of destination file
	 * @return
	 */

	public static boolean SaveFileByPhysicalDir(String physicalPath,
			InputStream istream) {
		
		boolean flag = false;
		try {
			OutputStream os = new FileOutputStream(physicalPath);
			int readBytes = 0;
			byte buffer[] = new byte[8192];
			while ((readBytes = istream.read(buffer, 0, 8192)) != -1) {
				os.write(buffer, 0, readBytes);
			}
			os.close();
			flag = true;
		} catch (FileNotFoundException e) {
			
			e.printStackTrace();
		} catch (IOException e) {
		
			e.printStackTrace();
		}
		return flag;
	}
	
	public static boolean CreateDirectory(String dir){
		File f = new File(dir);
		if (!f.exists()) {
			f.mkdirs();
		}
		return true;
	}
	
	
	public static void saveAsFileOutputStream(String physicalPath,String content) {
		  File file = new File(physicalPath);
		  boolean b = file.getParentFile().isDirectory();
		  if(!b){
			  File tem = new File(file.getParent());
			  // tem.getParentFile().setWritable(true);
			  tem.mkdirs();// 创建目录
		  }
		  //Log.info(file.getParent()+";"+file.getParentFile().isDirectory());
		  FileOutputStream foutput =null;
		  try {
			  foutput = new FileOutputStream(physicalPath);
			  
			  foutput.write(content.getBytes("UTF-8"));
			  //foutput.write(content.getBytes());
		  }catch(IOException ex) {
			  ex.printStackTrace();
			  throw new RuntimeException(ex);
		  }finally{
			  try {
				  foutput.flush();
				  foutput.close();
			  }catch(IOException ex){
				  ex.printStackTrace();
				  throw new RuntimeException(ex);
			  }
		  }
		  	//Log.info("文件保存成功:"+ physicalPath);
		 }

	
	
	 /**
     * COPY文件
     * @param srcFile String
     * @param desFile String
     * @return boolean
     */
    public boolean copyToFile(String srcFile, String desFile) {
        File scrfile = new File(srcFile);
        if (scrfile.isFile() == true) {
            int length;
            FileInputStream fis = null;
            try {
                fis = new FileInputStream(scrfile);
            }
            catch (FileNotFoundException ex) {
                ex.printStackTrace();
            }
            File desfile = new File(desFile);

            FileOutputStream fos = null;
            try {
                fos = new FileOutputStream(desfile, false);
            }
            catch (FileNotFoundException ex) {
                ex.printStackTrace();
            }
            desfile = null;
            length = (int) scrfile.length();
            byte[] b = new byte[length];
            try {
                fis.read(b);
                fis.close();
                fos.write(b);
                fos.close();
            }
            catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            scrfile = null;
            return false;
        }
        scrfile = null;
        return true;
    }

    /**
     * COPY文件夹
     * @param sourceDir String
     * @param destDir String
     * @return boolean
     */
    public boolean copyDir(String sourceDir, String destDir) {
        File sourceFile = new File(sourceDir);
        String tempSource;
        String tempDest;
        String fileName;
        File[] files = sourceFile.listFiles();
        for (int i = 0; i < files.length; i++) {
            fileName = files[i].getName();
            tempSource = sourceDir + "/" + fileName;
            tempDest = destDir + "/" + fileName;
            if (files[i].isFile()) {
                copyToFile(tempSource, tempDest);
            } else {
                copyDir(tempSource, tempDest);
            }
        }
        sourceFile = null;
        return true;
    }

    /**
     * 删除指定目录及其中的所有内容。
     * @param dir 要删除的目录
     * @return 删除成功时返回true,否则返回false。
     */
    public boolean deleteDirectory(File dir) {
        File[] entries = dir.listFiles();
        int sz = entries.length;
        for (int i = 0; i < sz; i++) {
            if (entries[i].isDirectory()) {
                if (!deleteDirectory(entries[i])) {
                    return false;
                }
            } else {
                if (!entries[i].delete()) {
                    return false;
                }
            }
        }
        if (!dir.delete()) {
            return false;
        }
        return true;
    }
    
    
    
    /**
     * File exist check
     *
     * @param sFileName File Name
     * @return boolean true - exist<br>
     *                 false - not exist
     */
    public static boolean checkExist(String sFileName) {
     
     boolean result = false;
       
       try {
    	   File f = new File(sFileName);
	   
    	   //if (f.exists() && f.isFile() && f.canRead()) {
	   if (f.exists() && f.isFile()) {
		    result = true;
	   } else {
		    result = false;
	   }
	   } catch (Exception e) {
	        result = false;
	   }
	       
        /* return */
        return result;
    }
   
    /**
     * Get File Size
     *
     * @param sFileName File Name
     * @return long File's size(byte) when File not exist return -1
     */
    public static long getSize(String sFileName) {
       
        long lSize = 0;
       
        try {
		    File f = new File(sFileName);
		           
		            //exist
		    if (f.exists()) {
			    if (f.isFile() && f.canRead()) {
			     lSize = f.length();
			    } else {
			     lSize = -1;
			    }
		            //not exist
		    } else {
		        lSize = 0;
		    }
	   } catch (Exception e) {
	        lSize = -1;
	   }
	   /* return */
	   return lSize;
    }
   
 /**
  * File Delete
  *
  * @param sFileName File Nmae
  * @return boolean true - Delete Success<br>
  *                 false - Delete Fail
  */
    public static boolean deleteFromName(String sFileName) {
  
        boolean bReturn = true;
  
        try {
            File oFile = new File(sFileName);
   
           //exist
           if (oFile.exists()) {
	           //Delete File
	           boolean bResult = oFile.delete();
	           //Delete Fail
	           if (bResult == false) {
	               bReturn = false;
	           }
	   
	           //not exist
           } else {
    
           }
   
	  } catch (Exception e) {
		  bReturn = false;
	  }
  
	  //return
	  return bReturn;
    }
   
 /**
  * File Unzip
  *
  * @param sToPath  Unzip Directory path
  * @param sZipFile Unzip File Name
  */
 @SuppressWarnings("rawtypes")
public static void releaseZip(String sToPath, String sZipFile) throws Exception {
  
  if (null == sToPath ||("").equals(sToPath.trim())) {
	   File objZipFile = new File(sZipFile);
	   sToPath = objZipFile.getParent();
  }
  ZipFile zfile = new ZipFile(sZipFile);
  Enumeration zList = zfile.entries();
  ZipEntry ze = null;
  byte[] buf = new byte[1024];
  while (zList.hasMoreElements()) {

	   ze = (ZipEntry) zList.nextElement();
	   if (ze.isDirectory()) {
	    continue;
	   }
	
	   OutputStream os =
	   new BufferedOutputStream(
	   new FileOutputStream(getRealFileName(sToPath, ze.getName())));
	   InputStream is = new BufferedInputStream(zfile.getInputStream(ze));
	   int readLen = 0;
	   while ((readLen = is.read(buf, 0, 1024)) != -1) {
		   os.write(buf, 0, readLen);
	   }
	   is.close();
	   os.close();
  }
  zfile.close();
 }
 
 /**
  * getRealFileName
  *
  * @param  baseDir   Root Directory
  * @param  absFileName  absolute Directory File Name
  * @return java.io.File     Return file
  */
 @SuppressWarnings({ "rawtypes", "unchecked" })
private static File getRealFileName(String baseDir, String absFileName) throws Exception {
  
  File ret = null;

  List dirs = new ArrayList();
  StringTokenizer st = new StringTokenizer(absFileName, System.getProperty("file.separator"));
  while (st.hasMoreTokens()) {
	  dirs.add(st.nextToken());
  }

  ret = new File(baseDir);
  if (dirs.size() > 1) {
	  for (int i = 0; i < dirs.size() - 1; i++) {
		  ret = new File(ret, (String) dirs.get(i));
	  }
  }
  if (!ret.exists()) {
	  ret.mkdirs();
  }
  ret = new File(ret, (String) dirs.get(dirs.size() - 1));
  return ret;
 }

 /**
  * copyFile
  *
  * @param  srcFile   Source File
  * @param  targetFile   Target file
  */
 @SuppressWarnings("resource")
 static public void copyFile(String srcFile , String targetFile) throws IOException
  {
  
   FileInputStream reader = new FileInputStream(srcFile);
   FileOutputStream writer = new FileOutputStream(targetFile);

   byte[] buffer = new byte [4096];
   int len;

   try
   {
	   reader = new FileInputStream(srcFile);
	   writer = new FileOutputStream(targetFile);
	   
	   while((len = reader.read(buffer)) > 0)
	   {
		   writer.write(buffer , 0 , len);
	   }
   }
   catch(IOException e)
   {
	   throw e;
   }
   finally
   {
	   if (writer != null)writer.close();
	   if (reader != null)reader.close();
   }
  }

 /**
  * renameFile
  *
  * @param  srcFile   Source File
  * @param  targetFile   Target file
  */
 static public void renameFile(String srcFile , String targetFile) throws IOException
  {
   try {
	   copyFile(srcFile,targetFile);
	   deleteFromName(srcFile);
   } catch(IOException e){
	   throw e;
   }
  }


 public static void write(String tivoliMsg,String logFileName) {
  try{
	   byte[]  bMsg = tivoliMsg.getBytes();
	   FileOutputStream fOut = new FileOutputStream(logFileName, true);
	   fOut.write(bMsg);
	   fOut.close();
  } catch(IOException e){
   //throw the exception      
  }

 }
 /**
 * This method is used to log the messages with timestamp,error code and the method details
 * @param errorCd String
 * @param className String
 * @param methodName String
 * @param msg String
 */
 public static void writeLog(String logFile, String batchId, String exceptionInfo) {
  
  DateFormat df = DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT, Locale.JAPANESE);
  
  Object args[] = {df.format(new Date()), batchId, exceptionInfo};
  
  String fmtMsg = MessageFormat.format("{0} : {1} : {2}", args);
  
  try {
   
   File logfile = new File(logFile);
   if(!logfile.exists()) {
    logfile.createNewFile();
   }
   
      FileWriter fw = new FileWriter(logFile, true);
      fw.write(fmtMsg);
      fw.write(System.getProperty("line.separator"));

      fw.flush();
      fw.close();

  } catch(Exception e) {
  }
 }
 
 public static String readTextFile(String realPath) throws Exception {
	 File file = new File(realPath);
	 	if (!file.exists()){
	 		System.out.println("File not exist!");
	 		return null;
	  }
	  BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(realPath),"UTF-8"));	  
	  String temp = "";
	  String txt="";
	  while((temp = br.readLine()) != null){
		  txt+=temp;
	   }	  
	  br.close();
	 return txt;
 }

 
}

 

2
1
分享到:
评论

相关推荐

    java File文件处理工具类

    Java中的`File`类是Java I/O流体系中不可或缺的一部分,它是用来操作...结合`FileUtils`这样的辅助工具类,我们可以编写出更简洁、易维护的代码。在实际开发中,还应考虑异常处理和错误恢复策略,以确保程序的健壮性。

    FileUtil.rar

    `FileUtil`可能提供了`uploadFile`方法,该方法会处理文件的读取、网络传输以及错误处理等细节,使得开发者无需关心底层实现,只需要传入文件路径和上传地址即可完成文件上传。 下载文件同样重要,`downloadFile`...

    java常用工具类封装util.rar

    8. **文件操作工具类(FileUtil)**:提供文件的创建、删除、移动、复制等操作,简化文件操作。例如`createFileIfNotExists()`用于创建文件(如果文件不存在),`deleteFile()`用于删除文件。 9. **网络工具类...

    hutool一个Java基础工具类

    Hutool提供了FileUtil工具类,支持文件的创建、删除、复制、移动等基本操作,还包含了文件的读写、查找、遍历等功能。例如,你可以轻松实现文件的复制: ```java FileUtil.copy(new File("源文件路径"), new File(...

    文件解压和压缩 解决中文乱码

    另一方面,`ZipFileUtil`可能是另一个自定义工具类,它不仅处理ZIP文件的压缩,还支持RAR文件的解压。在Java中,RAR格式的处理并不像ZIP那样内置在标准库中,通常需要第三方库如Apache Commons Compress或者JUnrar。...

    java实现rar压缩与解压缩

    在Java编程语言中,实现RAR压缩与解压缩是一项常见的任务,尤其在处理大量数据或打包文件以便于传输时。本文将深入探讨如何使用Java来实现这个功能,主要关注`FileUtil.java`文件中的代码实现。 首先,Java本身并不...

    java 文件处理

    6. **文件操作工具类FileUtil**:根据提供的`FileUtil.java`文件,这个工具类通常包含静态方法,便于执行常见的文件操作。可能包括读取文件到字符串、写字符串到文件、文件复制、删除、重命名等功能。例如: ```...

    Hutool (Java基础工具类).zip

    这个压缩包“Hutool (Java基础工具类).zip”包含了关于Hutool库的相关资料,如使用说明和可能的示例代码。 首先,Hutool的命名来源于“实用”和“工具”的英文单词"Util",它由多个模块组成,涵盖了日期时间处理、...

    java中常用操作

    - **`java.util.File`**:用于文件和目录的创建、删除、重命名等操作。 - **`java.io`包**:包含读写文件、输入输出流等I/O相关的类。 - **`java.util.concurrent`**:提供线程安全的工具类,如并发集合、锁等。 ...

    java文件上传

    - **文件保存逻辑**:获取文件的真实路径,然后使用`FileUtil`工具类复制文件到服务器。 #### 六、总结 通过上述步骤,我们可以在Java中利用Struts2框架轻松实现文件上传功能。需要注意的是,在实际部署时还需考虑...

Global site tag (gtag.js) - Google Analytics