1. 键盘录入一个新文件夹路径判断该路径是否存在 - 如果存在,则什么都不做 - 如果不存在,则创建该文件夹
时间: 2023-05-13 15:07:07 浏览: 91
可以使用以下代码实现:
import os
folder_path = input("请输入文件夹路径:")
if os.path.exists(folder_path):
print("该路径已存在")
else:
os.makedirs(folder_path)
print("文件夹创建成功")
相关问题
键盘录入一个文件夹路径打印所有文件夹路径后缀名
好的,我可以为您提供一个Java的示例代码来实现您的需求:
```java
import java.io.File;
public class PrintFolderPathsAndExtensions {
public static void main(String[] args) {
// 读取用户输入的文件夹路径
String folderPath = System.console().readLine("请输入文件夹路径:");
// 创建File对象
File folder = new File(folderPath);
// 打印所有文件夹路径和后缀名
printFolderPathsAndExtensions(folder);
}
private static void printFolderPathsAndExtensions(File folder) {
// 遍历文件夹中所有文件和子文件夹
for (File file : folder.listFiles()) {
// 如果是文件夹,则递归打印其下所有文件夹路径和后缀名
if (file.isDirectory()) {
printFolderPathsAndExtensions(file);
} else {
// 如果是文件,则打印其路径和后缀名
System.out.println(file.getAbsolutePath() + ",后缀名:" + getFileExtension(file));
}
}
}
private static String getFileExtension(File file) {
// 获取文件名
String fileName = file.getName();
// 获取文件名中最后一个"."的索引
int dotIndex = fileName.lastIndexOf(".");
// 如果文件名中没有"."或者"."在文件名的开头或结尾,则认为该文件没有后缀名
if (dotIndex == -1 || dotIndex == 0 || dotIndex == fileName.length() - 1) {
return "";
} else {
// 返回文件后缀名,不包含"."
return fileName.substring(dotIndex + 1);
}
}
}
```
使用该代码,您只需要在控制台中输入文件夹路径,即可打印出该文件夹中所有文件路径和后缀名。希望能够帮助到您!
java键盘录入一个文件夹路径,统计该文件夹(包含子文件夹)中文件个数和文件夹个数。
可以使用递归来遍历文件夹中的所有文件和子文件夹,并统计它们的个数。以下是一个示例代码:
```java
import java.io.File;
public class FileCounter {
public static void main(String[] args) {
// 读取用户输入的文件夹路径
System.out.print("请输入文件夹路径:");
String path = System.console().readLine();
// 统计文件夹和文件的个数
int folderCount = 0;
int fileCount = 0;
File folder = new File(path);
countFiles(folder, folderCount, fileCount);
// 输出统计结果
System.out.println("文件夹个数:" + folderCount);
System.out.println("文件个数:" + fileCount);
}
public static void countFiles(File folder, int folderCount, int fileCount) {
if (folder.isDirectory()) {
folderCount++; // 统计文件夹个数
File[] files = folder.listFiles();
if (files != null) {
for (File file : files) {
countFiles(file, folderCount, fileCount);
}
}
} else {
fileCount++; // 统计文件个数
}
}
}
```
在上面的代码中,我们首先读取用户输入的文件夹路径,然后定义了两个变量 `folderCount` 和 `fileCount`,分别用于统计文件夹和文件的个数。接着,我们使用 `File` 类来创建一个文件夹实例,并调用 `countFiles()` 方法来统计文件夹中的文件和子文件夹个数。在 `countFiles()` 方法中,我们首先判断当前文件是否是一个文件夹,如果是,则增加文件夹个数,并递归调用 `countFiles()` 方法来遍历当前文件夹中的所有文件和子文件夹。如果当前文件不是一个文件夹,那么我们就增加文件个数。最后,在主方法中输出统计结果。
注意:上述代码并没有处理异常情况,如输入的路径不存在或者无法访问等情况。在实际开发中,还需要对这些异常情况进行适当的处理。