欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

java文件操作工具類分享(file文件工具類)

 更新時間:2014年01月28日 15:28:41   作者:  
java文件操作工具類(文件工具類)

復(fù)制代碼 代碼如下:

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();// 創(chuàng)建目錄
    }
    //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;
    }

    /**
     * 刪除指定目錄及其中的所有內(nèi)容。
     * @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;
 }
}

相關(guān)文章

  • 圖文詳解mybatis+postgresql平臺搭建步驟

    圖文詳解mybatis+postgresql平臺搭建步驟

    從頭開始搭建一個mybatis+postgresql平臺,這篇文章主要介紹了圖文詳解mybatis+postgresql平臺搭建步驟,感興趣的小伙伴們可以參考一下
    2016-07-07
  • Spring Data JPA 如何使用QueryDsl查詢并分頁

    Spring Data JPA 如何使用QueryDsl查詢并分頁

    這篇文章主要介紹了Spring Data JPA 如何使用QueryDsl查詢并分頁,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-11-11
  • java區(qū)分絕對路徑和相對路徑的方法

    java區(qū)分絕對路徑和相對路徑的方法

    這篇文章主要介紹了java區(qū)分絕對路徑和相對路徑的方法,實例分析了java針對路徑操作的相關(guān)技巧,需要的朋友可以參考下
    2015-04-04
  • java清除html轉(zhuǎn)義字符

    java清除html轉(zhuǎn)義字符

    這篇文章主要介紹了一個靜態(tài)文件處理的一些便捷服務(wù),包括 java清除html轉(zhuǎn)義字符,清除html代碼,從style樣式中讀取CSS的屬性,將字符串截取指定長度,涉及l(fā)og4j,common-lang類的學(xué)習(xí)
    2014-01-01
  • @FeignClient注解中屬性contextId的使用說明

    @FeignClient注解中屬性contextId的使用說明

    這篇文章主要介紹了@FeignClient注解中屬性contextId的使用說明,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-06-06
  • java中文分詞之正向最大匹配法實例代碼

    java中文分詞之正向最大匹配法實例代碼

    中文分詞應(yīng)用很廣泛,網(wǎng)上也有很多開源項目,下面這篇文章主要給大家介紹了關(guān)于java中文分詞之正向最大匹配法的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),需要的朋友可以參考借鑒,下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧。
    2017-11-11
  • MyBatis 配置之集合的嵌套方式

    MyBatis 配置之集合的嵌套方式

    這篇文章主要介紹了MyBatis 配置之集合的嵌套方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-09-09
  • Springboot實現(xiàn)發(fā)送郵件

    Springboot實現(xiàn)發(fā)送郵件

    這篇文章主要為大家詳細(xì)介紹了Springboot實現(xiàn)發(fā)送郵件功能,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2021-10-10
  • Spring的@PropertySource注解源碼解析

    Spring的@PropertySource注解源碼解析

    這篇文章主要介紹了Spring的@PropertySource注解源碼解析,就以源碼時序圖的方式,直觀的感受下@PropertySource注解在Spring源碼層面的執(zhí)行流程,需要的朋友可以參考下
    2023-11-11
  • Spring中AOP注解@Aspect的使用詳解

    Spring中AOP注解@Aspect的使用詳解

    這篇文章主要介紹了Spring中AOP注解@Aspect的使用詳解,AOP是種面向切面的編程思想,面向切面編程是將程序抽象成各個切面,將那些影響了多個類的公共行為抽取到一個可重用模塊里,減少系統(tǒng)的重復(fù)代碼,降低模塊間的耦合度,增強代碼的可操作性和可維護性,需要的朋友可以參考下
    2024-01-01

最新評論