關於文件File操作的工具類

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.util.ArrayList;
import java.util.List;

import org.laya.io.IOUtils;

/**
 * 文件操作工具類
 */
public class FileUtil {
	/**
	 * 創建文件夾
	 * @param path
	 * @return
	 */
	public static File createPath(String path){ 
		File file = new File(path);
		if(!file.exists()){ 
			file.mkdirs();
		}
		return file;
	}
	
	/**
	 * 創建文件
	 * @param path
	 * @param fileName
	 */
	public static File createFile(String path,String fileName){
		File dirs = new File(path);
		if(!dirs.exists()){
			dirs.mkdirs();
		}
		File file = new File(path+File.separator+fileName);
		if(!file.exists()){
			try {
				file.createNewFile();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return file;
	}
	
	/**
	 * 判斷是否存在
	 * @param path
	 * @param fileName
	 * @return
	 */
	public static boolean isExist(String path,String fileName){
		File dirs = new File(path);
		if(!dirs.exists()){
			return false;
		}
		File file = new File(path+fileName);
		if(!file.exists()){
			return false;
		}
		return true;
	}
	
	/**
	 * 清空文件內容
	 * @param file
	 */
	public static void clear(File file){
		FileWriter fw;
		try {
			fw = new FileWriter(file);
			fw.write("");
			fw.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 向文件中寫入數據
	 * @param file
	 * @param str
	 */
	public static void write(File file,String str){
		FileWriter fw;
		try {
			fw = new FileWriter(file);
			fw.write(str);
			fw.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
     * A方法追加文件:使用RandomAccessFile
     */
    public static void appendMethod(String fileName, String content) {
        try {
            // 打開一個隨機訪問文件流,按讀寫方式
            RandomAccessFile randomFile = new RandomAccessFile(fileName, "rw");
            // 文件長度,字節數
            long fileLength = randomFile.length();
            //將寫文件指針移到文件尾。
            randomFile.seek(fileLength);
            randomFile.writeBytes(content);
            randomFile.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * B方法追加文件:使用FileWriter
     */
    public static void append(File file, String content) {
    	String fileName = file.getAbsolutePath();
        try {
            //打開一個寫文件器,構造函數中的第二個參數true表示以追加形式寫文件
            FileWriter writer = new FileWriter(fileName, true);
            writer.write(content);
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 以行爲單位讀取文件,常用於讀面向行的格式化文件
     */
    public static List<String> readFileByLines(File file) {
    	List<String> list = new ArrayList<String>();
        BufferedReader reader = null;
        try {
//            System.out.println("以行爲單位讀取文件內容,一次讀一整行:");
            reader = new BufferedReader(new FileReader(file));
            String tempString = null;
//            int line = 1;
            // 一次讀入一行,直到讀入null爲文件結束
            while ((tempString = reader.readLine()) != null) {
                // 顯示行號
//                System.out.println("line " + line + ": " + tempString);
            	list.add(tempString);
//            	return tempString;
//                line++;
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e1) {
                }
            }
        }
        return list;
    }
    
    /**
     * 以行爲單位向文件中寫入內容
     * @param path
     * @param filename
     * @param list    內容集合
     * @return
     */
    public static File writeFileByLines(File file,List<String> list) {
    	try {
			FileWriter fw= new FileWriter(file);
			BufferedWriter  bw=new BufferedWriter(fw);
			for (String string : list) {
				bw.write(string+"\t\n");
			}
			bw.close();
	        fw.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	return file;
    }
    
    /**
    * 複製單個文件
    * @param oldPath String 原文件路徑 如:c:/fqf.txt
    * @param newPath String 複製後路徑 如:f:/fqf.txt
    * @return boolean
    */
	public void copyFile(String oldPath, String newPath) {
		try {
			int bytesum = 0;
			int byteread = 0;
			File oldfile = new File(oldPath);
			if (oldfile.exists()) { // 文件存在時
				InputStream inStream = new FileInputStream(oldPath); // 讀入原文件
				FileOutputStream fs = new FileOutputStream(newPath);
				byte[] buffer = new byte[1444];
				int length;
				while ((byteread = inStream.read(buffer)) != -1) {
					bytesum += byteread; // 字節數 文件大小
					System.out.println(bytesum);
					fs.write(buffer, 0, byteread);
				}
				inStream.close();
			}
		} catch (Exception e) {
			System.out.println("複製單個文件操作出錯");
			e.printStackTrace();

		}
	}

	/**
	 * 刪除本級 以及內部的文件
	 * @param path
	 */
	public static void delFiles(File file) {
		if(file==null){
			return;
		}
		try {
			if (file.isDirectory()) {
				String[] chlidren = file.list();
				for (int i = 0; i < chlidren.length; i++) {
					IOUtils.forceDelete(new File(file+File.separator+chlidren[i]));
				}
			}
			IOUtils.forceDelete(file);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章