java file如何负责
文件读取与写入
使用 FileInputStream 和 FileOutputStream 实现文件的字节流读写。适用于二进制文件或非文本文件。
try (FileInputStream fis = new FileInputStream("input.txt");
FileOutputStream fos = new FileOutputStream("output.txt")) {
int byteData;
while ((byteData = fis.read()) != -1) {
fos.write(byteData);
}
} catch (IOException e) {
e.printStackTrace();
}
文本文件处理
通过 BufferedReader 和 BufferedWriter 高效处理文本文件,支持逐行读写。
try (BufferedReader br = new BufferedReader(new FileReader("input.txt"));
BufferedWriter bw = new BufferedWriter(new FileWriter("output.txt"))) {
String line;
while ((line = br.readLine()) != null) {
bw.write(line);
bw.newLine();
}
} catch (IOException e) {
e.printStackTrace();
}
文件属性操作
利用 File 类检查文件是否存在、获取文件大小、删除文件等操作。
File file = new File("example.txt");
boolean exists = file.exists();
long fileSize = file.length();
boolean deleted = file.delete();
NIO 文件操作
Java NIO 提供 Files 和 Paths 类,简化文件复制、移动等操作。
Path source = Paths.get("source.txt");
Path target = Paths.get("target.txt");
Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING);
临时文件创建
使用 File.createTempFile() 生成临时文件,避免命名冲突。
File tempFile = File.createTempFile("temp_", ".txt");
tempFile.deleteOnExit(); // JVM退出时删除
文件监控
通过 WatchService 监控目录下的文件变更事件(创建、修改、删除)。

WatchService watchService = FileSystems.getDefault().newWatchService();
Path path = Paths.get("directory_to_watch");
path.register(watchService, StandardWatchEventKinds.ENTRY_MODIFY);
WatchKey key;
while ((key = watchService.take()) != null) {
for (WatchEvent<?> event : key.pollEvents()) {
System.out.println("Event kind:" + event.kind() + ". File affected: " + event.context());
}
key.reset();
}






