Elyar的java笔记--Java简单文件操作

来源:互联网 发布:网络新词贫民窟女孩 编辑:程序博客网 时间:2024/06/01 07:45

简单的文件操作:检查指定路径文件是否存在,创建文件,删除文件


测试

package com.cn.elyarimport java.io.File;/** * @author Elyar * @version 1.0 */public class Test {/** * 主函数 *  * @param args */public static void main(String[] args) {String path = new String("D:/text2");UtilFile.createFile(path);// UtilFile.delectFile(path);}}

文件工具类:

package com.cn.elyar;import java.io.File;import java.io.IOException;import java.lang.reflect.Field;public class UtilFile {/** * 创建文件 *  * @param path *            文件地址 */public static void createFile(String path) {File file = new File(path);// 判断文件是否存在if (cheakFile(file)) {// 文件存在System.out.println("该文件已存在");if (file.isFile()) {// 文件类型为文件System.out.println("该文件类型为:文件");} else if (file.isDirectory()) {// 文件类型为文件夹System.out.println("该文件类型为:文件夹");}} else {// 文件不存在file.mkdir();System.out.println("文件夹创建成功");try {String filePath = file.getPath();File createFile = new File(filePath + "/Elyar.txt");// 指定路径的文件对象createFile.createNewFile();// 创建文件System.out.println("文件创建成功");} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}public static void delectFile(String path) {File file = new File(path);// 检查文件是否存在if (cheakFile(file)) {// 文件存在/** * 若为文件夹则检查是否存在子文件,否则不能进行删除 *  * 若为文件类型则可以直接进行删除操作 */if (file.isDirectory()) {// 该文件为文件夹// 检验文件夹是否为空if (file.length() != 0) {// 不为空System.out.println("该路径包含有其他文件不可删除");} else {file.delete();// 删除文件System.out.println("文件已删除");}} else if (file.isFile()) {// 该文件为文件类型file.delete();// 删除文件System.out.println("文件已删除");}} else {// 文件不存在System.out.println("删除失败!该文件不存在");}}/** * 检验文件是否存在 *  * @param target *            目标文件 * @return 存在反回true 不存在返回false */private static boolean cheakFile(File target) {if (target.exists()) {// 文件存在return true;// 文件存在}return false;// 文件不存在}}


0 0