创建文件及文件夹以及删除文件及文件夹

本文介绍了如何使用Java实现文件路径操作,包括创建文件、文件夹和删除文件夹的方法。通过FileOperation类展示了如何添加文件并删除指定路径的文件夹。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package com.hzh.Operation;

import java.io.File;
import java.io.IOException;

/**

  • @Description:
  • @date: 2021年4月22日下午10:02:31
    */

public class FileOperation {
public static void main(String[] args) {

	String filePath = "C:\\Users\\小太阳\\Desktop\\java\\wwwwww\\asdsa\\asdasd\\gfhgf\\werew\\w";
	String delPath = "C:\\\\Users\\\\小太阳\\\\Desktop\\\\java\\\\wwwwww";
	String fileName = "qqq.yxy";

	addFile(filePath, fileName);

	deleteFold(new File(delPath));

}

/**
 * @Description: 创建文件夹及文件
 * @param filePath
 * @param fileName
 */
public static void addFile(String filePath, String fileName) {

	StringBuilder builder = new StringBuilder();
	String pathName = builder.append(filePath).append("\\").append(fileName).toString();
	System.out.println(pathName);
	File file1 = new File(filePath);
	File file2 = new File(pathName);

	System.out.println((!file1.exists()) || (!file2.exists()));
	if ((!file1.exists()) || (!file2.exists())) {
		try {
			file1.mkdirs();
			file2.createNewFile();
			System.out.println("创建成功");
		} catch (IOException e) {
			System.out.println("创建失败");
		}
	}

}

/**
 * @Description: 删除文件夹
 * @param delFile
 * @return
 */
public static boolean deleteFold(File delFile) {
	if (!delFile.exists()) {
		System.out.println("文件夹 " + delFile.getAbsolutePath() + "不存在");
		return false;
	}
	// 文件夹
	if (delFile.isDirectory()) {
		File[] files = delFile.listFiles();
		for (File subFile : files) {
			boolean isSuccess = deleteFold(subFile);
			if (!isSuccess) {
				return isSuccess;
			}
		}
	} else {
		boolean isSuccess = delFile.delete();
		if (!isSuccess) {
			return isSuccess;
		}
	}
	if (delFile.isDirectory()) {
		return delFile.delete();
	} else {
		return true;
	}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值