FileUtil

import java.io.File;

/**
 * 文件工具类
 * user: chenjinbo
 * date: 2013-04-11
 */
public class FileUtil {
    /**
     * 检查文件是否存在
     *
     * @param filePath
     * @return
     */
    public static boolean checkFileExist(String filePath) {
        File file = new File(filePath);
        return file.exists();
    }

    /**
     * 创建文件
     *
     * @param filePath
     * @return
     */
    public static File createFile(String filePath) {
        File file = new File(filePath);
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        try {
            boolean createSuccessed = file.createNewFile();
            if (!createSuccessed) {
                return null;
            }
        } catch (Exception e) {
            return null;
        }
        return file;
    }

    public static void main(String[] args) {
        String filePath = "C:/myfolder/stop.txt";
        System.out.println(checkFileExist(filePath));
        if (!checkFileExist(filePath)) {
            if (createFile(filePath) == null) {
                System.out.println("创建失败");
            } else {
                System.out.println("创建成功");
            }
        }
    }
}

 

你可能感兴趣的:(fileutil)