前置知识:
1.file类和files类
一句话总结:file在java.io包内,files在java.nio包内,files提供了更多的静态函数来执行文件操作,比如将字符串写入文件,功能更加强大。
- String Files.readString(Path path)
- String Files.readString(Path, Charset)
- Path Files.write(Path, CharSequence, OpenOption...)
- Path Files.write(Path, CharSequence, Charset, OpenOption...)
File
类用于表示文件或目录的路径名。它可以用于创建、删除、重命名文件或目录,以及获取文件属性等。有常见方法如下:
// 1. 创建新文件
boolean created = file.createNewFile();
// 2. 获取文件名和路径
String fileName = file.getName();
String filePath = file.getPath();
// 3. 检查文件是否存在
boolean exists = file.exists();
// 4. 创建目录
File directory = new File("example_directory");
boolean dirCreated = directory.mkdir();
// 5. 检查是否为目录
boolean isDirectory = directory.isDirectory();
Files
类是 Java NIO 中提供的一个实用工具类,用于执行文件和目录操作。与 File
类不同,Files
类提供了更现代、功能更强大的路径操作,包括复制、移动、删除文件或目录,以及读写文件内容等。
import java.nio.file.*;
import java.io.IOException;
public class FilesExample {
public static void main(String[] args) {
// 1. 复制文件
Path sourcePath = Paths.get("source.txt");
Path destinationPath = Paths.get("destination.txt");
try {
Files.copy(sourcePath, destinationPath, StandardCopyOption.REPLACE_EXISTING);
System.out.println("文件复制成功");
} catch (IOException e) {
e.printStackTrace();
}
// 2. 移动文件
Path sourceFile = Paths.get("fileToMove.txt");
Path destinationFolder = Paths.get("destinationFolder");
try {
Files.move(sourceFile, destinationFolder.resolve(sourceFile.getFileName()), StandardCopyOption.REPLACE_EXISTING);
System.out.println("文件移动成功");
} catch (IOException e) {
e.printStackTrace();
}
// 3. 删除文件或目录
Path fileToDelete = Paths.get("fileToDelete.txt");
try {
Files.delete(fileToDelete);
System.out.println("文件删除成功");
} catch (IOException e) {
e.printStackTrace();
}
// 4. 读取文件内容
Path filePathToRead = Paths.get("readMe.txt");
try {
byte[] fileContent = Files.readAllBytes(filePathToRead);
String contentString = new String(fileContent);
System.out.println("文件内容:\n" + contentString);
} catch (IOException e) {
e.printStackTrace();
}
// 5. 写入文件内容
Path filePathToWrite = Paths.get("writeMe.txt");
String contentToWrite = "Hello, Files class!";
try {
Files.write(filePathToWrite, contentToWrite.getBytes(), StandardOpenOption.CREATE);
System.out.println("文件写入成功");
} catch (IOException e) {
e.printStackTrace();
}
}
}