可以使用递归的方式来清空文件夹下所有的文件。以下是一个示例代码:
import java.io.File; public class ClearFolder { public static void main(String[] args) { String folderPath = "C:/path/to/folder"; clearFolder(folderPath); } public static void clearFolder(String folderPath) { File folder = new File(folderPath); if (folder.exists() && folder.isDirectory()) { File[] files = folder.listFiles(); if (files != null) { for (File file : files) { if (file.isDirectory()) { clearFolder(file.getAbsolutePath()); } else { file.delete(); } } } } } }
在上面的示例中,clearFolder
方法会递归地清空指定文件夹下的所有文件。首先,它会检查文件夹是否存在并且是一个文件夹。如果是,它会获取文件夹中的所有文件,并对每个文件进行处理。如果文件是一个文件夹,则递归调用clearFolder
方法来清空该文件夹。如果文件是一个文件,则直接删除。
要清空的文件夹路径可以根据实际情况进行修改。