创建一个java记事本管理器。要求如下: ①从键盘上输入1,在当前目录下创建文件iotest6txt②从键盘上输入2,将E盘iotest2txt复制iotest3txt. ③从键盘上输入3,修改E盘iotest3txt文件的内容为”修改文件3内容“. 4.从键盘上输入4.统计当前目录下文件的个数,并输出每 个文件的文件名,大小,最近修改时间。
时间: 2024-02-15 15:06:00 浏览: 142
用java实现记事本
好的,以下是一个基本的Java记事本管理器的实现,你可以根据需要进行修改和优化。
```
import java.io.*;
import java.nio.file.*;
import java.nio.file.attribute.*;
import java.text.SimpleDateFormat;
import java.util.*;
public class MyFileManager {
public static void main(String[] args) throws IOException {
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("Please select an operation:");
System.out.println("1. Create file");
System.out.println("2. Copy file");
System.out.println("3. Modify file");
System.out.println("4. List files");
System.out.println("5. Quit");
String choice = scanner.nextLine();
switch (choice) {
case "1":
createFile();
break;
case "2":
copyFile();
break;
case "3":
modifyFile();
break;
case "4":
listFiles();
break;
case "5":
System.exit(0);
default:
System.out.println("Invalid choice. Please try again.");
break;
}
}
}
public static void createFile() throws IOException {
String filename = "iotest6.txt";
Path path = Paths.get(filename);
if (!Files.exists(path)) {
Files.createFile(path);
System.out.println("File " + filename + " created successfully!");
} else {
System.out.println("File already exists!");
}
}
public static void copyFile() throws IOException {
Path srcPath = Paths.get("E:/iotest2.txt");
Path destPath = Paths.get("iotest3.txt");
if (Files.exists(srcPath)) {
Files.copy(srcPath, destPath, StandardCopyOption.REPLACE_EXISTING);
System.out.println(srcPath + " copied to " + destPath + " successfully!");
} else {
System.out.println(srcPath + " does not exist!");
}
}
public static void modifyFile() throws IOException {
String filename = "iotest3.txt";
Path path = Paths.get(filename);
if (Files.exists(path)) {
Files.write(path, "Modified file 3 content.\n".getBytes());
System.out.println("File " + filename + " modified successfully!");
} else {
System.out.println("File does not exist!");
}
}
public static void listFiles() throws IOException {
DirectoryStream.Filter<Path> filter = new DirectoryStream.Filter<Path>() {
@Override
public boolean accept(Path entry) throws IOException {
return Files.isRegularFile(entry);
}
};
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try (DirectoryStream<Path> stream = Files.newDirectoryStream(Paths.get("."), filter)) {
for (Path path : stream) {
BasicFileAttributes attrs = Files.readAttributes(path, BasicFileAttributes.class);
long size = attrs.size();
String mtime = sdf.format(new Date(attrs.lastModifiedTime().toMillis()));
System.out.println(path.getFileName() + "\t" + size + "\t" + mtime);
}
System.out.println("Total " + ((List<Path>) stream).size() + " files in the current directory.");
}
}
}
```
请注意,此代码忽略了文件类型,所以如果你的当前目录下有子目录或其他非文件类型的项目,它们也会被列出来。此外,此代码假定你的Java程序在当前目录下运行,并且使用了Java 8的新特性,如果你使用其他版本的Java或其他操作系统,需要进行修改。
阅读全文