请帮我写一个基于Java的文件管理系统
时间: 2023-08-28 09:25:45 浏览: 42
好的,下面是一个基于Java的简单文件管理系统的示例代码,包括基本的文件操作功能:
```java
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class FileManager {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String command;
System.out.println("Welcome to the File Manager System.");
while (true) {
System.out.print("Enter a command (list, create, delete, rename, exit): ");
command = scanner.nextLine();
if (command.equalsIgnoreCase("list")) {
listFiles();
} else if (command.equalsIgnoreCase("create")) {
createFile(scanner);
} else if (command.equalsIgnoreCase("delete")) {
deleteFile(scanner);
} else if (command.equalsIgnoreCase("rename")) {
renameFile(scanner);
} else if (command.equalsIgnoreCase("exit")) {
System.out.println("Exiting the program.");
break;
} else {
System.out.println("Invalid command. Please enter a valid command.");
}
}
}
private static void listFiles() {
File directory = new File(".");
File[] files = directory.listFiles();
for (File file : files) {
System.out.println(file.getName());
}
}
private static void createFile(Scanner scanner) {
System.out.print("Enter the name of the file to create: ");
String fileName = scanner.nextLine();
File file = new File(fileName);
try {
if (file.createNewFile()) {
System.out.println("File created successfully.");
} else {
System.out.println("File already exists.");
}
} catch (IOException e) {
System.out.println("Error occurred while creating file.");
e.printStackTrace();
}
}
private static void deleteFile(Scanner scanner) {
System.out.print("Enter the name of the file to delete: ");
String fileName = scanner.nextLine();
File file = new File(fileName);
if (file.delete()) {
System.out.println("File deleted successfully.");
} else {
System.out.println("Failed to delete file. File may not exist or is currently in use.");
}
}
private static void renameFile(Scanner scanner) {
System.out.print("Enter the name of the file to rename: ");
String oldName = scanner.nextLine();
File oldFile = new File(oldName);
if (!oldFile.exists()) {
System.out.println("File does not exist. Cannot rename.");
return;
}
System.out.print("Enter the new name of the file: ");
String newName = scanner.nextLine();
File newFile = new File(newName);
if (newFile.exists()) {
System.out.println("File already exists. Cannot rename.");
return;
}
if (oldFile.renameTo(newFile)) {
System.out.println("File renamed successfully.");
} else {
System.out.println("Failed to rename file.");
}
}
}
```
这个示例程序实现了文件管理系统的基本功能,包括列出当前目录下的文件、创建文件、删除文件和重命名文件。您可以根据需要对代码进行修改和扩展。