java 遍历本地文件夹并且在每一个目录下创建1.txt文件,在txt文件中写入内容 删除所有目录及文件
时间: 2024-03-27 22:36:08 浏览: 108
好的,我可以为您提供Java的代码实现。
首先,我们需要使用递归来遍历本地文件夹并且在每一个目录下创建1.txt文件。代码如下:
```java
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class CreateFile {
public static void main(String[] args) {
String path = "your/local/folder/path";
File folder = new File(path);
createTxtFile(folder);
}
public static void createTxtFile(File folder) {
if (folder.isDirectory()) {
//创建1.txt文件
File file = new File(folder.getPath() + File.separator + "1.txt");
try {
file.createNewFile();
//写入内容
FileWriter writer = new FileWriter(file);
writer.write("This is a test content.");
writer.flush();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
//遍历子目录
File[] files = folder.listFiles();
for (File file : files) {
createTxtFile(file);
}
}
}
}
```
上述代码中,您需要将 `path` 替换为您要遍历的本地文件夹路径。程序会递归遍历该文件夹下的所有目录,并且在每个目录下创建 `1.txt` 文件,并写入内容 "This is a test content."。
接下来,我们需要删除所有目录及文件。代码如下:
```java
import java.io.File;
public class DeleteFile {
public static void main(String[] args) {
String path = "your/local/folder/path";
File folder = new File(path);
deleteFolder(folder);
}
public static void deleteFolder(File folder) {
if (folder.isDirectory()) {
//删除文件夹下所有文件及子目录
File[] files = folder.listFiles();
for (File file : files) {
deleteFolder(file);
}
}
//删除文件夹本身
folder.delete();
}
}
```
同样地,您需要将 `path` 替换为您要删除的本地文件夹路径。程序会递归删除该文件夹下的所有目录及文件。
希望能够帮助到您!
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![java](https://img-home.csdnimg.cn/images/20250102104920.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)