Java操作文件工具包

package cn.lk.Utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.charset.Charset;

public class FileUtil {

    /**
     * 讀取指定文件內容
     * @param path  文件路徑
     * @return 讀取的內容
     */
    public static String readForFile(String path){
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader(path));
            String line = reader.readLine();
            return line;
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return "";
        } finally{
            try {
                reader.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    /**
     * 向指定文件寫入內容
     * @param path 文件路徑
     * @param msg 要寫入的信息
     */
    public static void writeToFile(String path,String msg){
        FileWriter fw = null;
        try {
            fw = new FileWriter(path);
            fw.write(msg);
        } catch (IOException e) {
            e.printStackTrace();
        } finally{
            try {
                fw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 判斷文件是否存在
     * @param path 文件路徑
     */
    public static void fileIsExist(String path) {
         File file=new File(path);    
         if(!file.exists())    
         {    
             try {    
                 file.createNewFile();    
             } catch (IOException e) {    
                 // TODO Auto-generated catch block    
                 e.printStackTrace();    
             }    
         }  
    }

    /**
     * 判斷文件夾是否存在
     * @param path 文件夾路徑
     */
    public static void folderIsExist(String path) {
        File file = new File(path);
        // 判斷文件夾是否存在,如果不存在則創建文件夾
        if (!file.exists()) {
            file.mkdir();
        }
    }
}

轉載請註明鏈接地址

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