文件操作技术
文件读取策略
读取文本文件
import java.nio.file.Files;
import java.nio.file.Paths;
import java.io.IOException;
import java.util.List;
public class FileReader {
// 将整个文件读取为字符串
public static void readWholeFile() throws IOException {
String content = Files.readString(Paths.get("/home/labex/example.txt"));
}
// 逐行读取文件
public static void readLineByLine() throws IOException {
List<String> lines = Files.readAllLines(Paths.get("/home/labex/example.txt"));
lines.forEach(System.out::println);
}
}
读取二进制文件
public class BinaryFileReader {
public static byte[] readBinaryFile() throws IOException {
return Files.readAllBytes(Paths.get("/home/labex/data.bin"));
}
}
文件写入技术
graph TD
A[文件写入方法] --> B[写入全部内容]
A --> C[追加到文件]
A --> D[逐行写入]
A --> E[写入二进制数据]
写入文本文件
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
public class FileWriter {
// 写入全部内容
public static void writeWholeFile() throws IOException {
Files.writeString(
Paths.get("/home/labex/output.txt"),
"Hello, LabEx!"
);
}
// 追加到文件
public static void appendToFile() throws IOException {
Files.writeString(
Paths.get("/home/labex/log.txt"),
"New log entry\n",
StandardOpenOption.APPEND
);
}
}
文件操作
操作 |
方法 |
描述 |
复制 |
Files.copy() |
将文件从源复制到目标 |
移动 |
Files.move() |
移动或重命名文件 |
删除 |
Files.delete() |
从文件系统中删除文件 |
高级文件操作
import java.nio.file.*;
public class FileManipulator {
// 带选项复制文件
public static void copyFileWithOptions() throws IOException {
Path source = Paths.get("/home/labex/source.txt");
Path destination = Paths.get("/home/labex/destination.txt");
Files.copy(
source,
destination,
StandardCopyOption.REPLACE_EXISTING,
StandardCopyOption.COPY_ATTRIBUTES
);
}
// 移动文件
public static void moveFile() throws IOException {
Path source = Paths.get("/home/labex/oldlocation.txt");
Path destination = Paths.get("/home/labex/newlocation.txt");
Files.move(
source,
destination,
StandardCopyOption.REPLACE_EXISTING
);
}
}
文件属性和元数据
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.BasicFileAttributes;
public class FileAttributeReader {
public static void readFileAttributes() throws IOException {
Path filePath = Paths.get("/home/labex/example.txt");
// 读取基本文件属性
BasicFileAttributes attrs = Files.readAttributes(
filePath,
BasicFileAttributes.class
);
System.out.println("大小: " + attrs.size());
System.out.println("创建时间: " + attrs.creationTime());
System.out.println("最后修改时间: " + attrs.lastModifiedTime());
}
}
文件操作中的错误处理
import java.nio.file.*;
public class FileErrorHandling {
public static void safeFileOperation() {
try {
Path filePath = Paths.get("/home/labex/example.txt");
Files.delete(filePath);
} catch (NoSuchFileException e) {
System.out.println("文件不存在");
} catch (AccessDeniedException e) {
System.out.println("权限被拒绝");
} catch (IOException e) {
System.out.println("发生意外错误");
}
}
}
结论
掌握文件操作技术对Java开发者至关重要。LabEx建议通过实践这些方法来构建强大的文件处理应用程序。