Files:轻松复制、移动、删除或处理文件的工具类,有你需要的所有方法
public class FilesDemo {
public static void main(String[] args) throws IOException {
Path path = Paths.get("D:/work/zk/opensource/javase/ThinkingInJava/bak.txt");
//Path file = Files.createFile(path);
//System.out.println(file);
Files.delete(path);
}
public static void copy() throws IOException {
Path source = Paths.get("D:/work/zk/opensource/javase/ThinkingInJava/bak.txt");
Path target = Paths.get("D:/demo.txt");
//copy 可以设置选项 move方法类似
Files.copy(source,target);
}
public static void read(){
Path file = Paths.get("D:/work/zk/opensource/javase/ThinkingInJava/bak.txt");
try(BufferedReader reader = Files.newBufferedReader(file, StandardCharsets.UTF_8)){
String line;
while ((line = reader.readLine())!=null){
System.out.println(line);
}
}catch (IOException e){
}
}
public static void write(){
Path file = Paths.get("D:/work/zk/opensource/javase/ThinkingInJava/bak.txt");
try(BufferedWriter writer = Files.newBufferedWriter(file, StandardCharsets.UTF_8, StandardOpenOption.WRITE)){
//从头写
//writer.write("hello world");
writer.append("hello world");
}catch (IOException e){
}
}
//简化读写
public static void simpleRead() throws IOException{
Path file = Paths.get("D:/work/zk/opensource/javase/ThinkingInJava/bak.txt");
List<String> allLines = Files.readAllLines(file, StandardCharsets.UTF_8);
for (String line : allLines) {
System.out.println(line);
}
}
public static void simpleRead2() throws IOException{
Path file = Paths.get("D:/work/zk/opensource/javase/ThinkingInJava/bak.txt");
byte[] bytes = Files.readAllBytes(file);
System.out.println(new String(bytes));
}
}
WatchService:用来监视文件或目录的核心类,不管它们有没有变化
import java.io.IOException;
import java.nio.file.*;
import static java.nio.file.StandardWatchEventKinds.*;
public class WatchServiceDemo {
private static boolean shutdown = false;
public static void main(String[] args) {
try {
WatchService watcher = FileSystems.getDefault().newWatchService();
//监听D盘根目录
Path dir = FileSystems.getDefault().getPath("D:/");
WatchKey key = dir.register(watcher, ENTRY_CREATE,ENTRY_DELETE);
while (!shutdown) {
key = watcher.take();
for (WatchEvent<?> event : key.pollEvents()) {
//如果有修改 则发出通知
if (event.kind() == ENTRY_CREATE) {
System.out.println("有文件创建");
}
if (event.kind() == ENTRY_DELETE) {
System.out.println("有文件删除");
}
}
key.reset();
}
} catch (IOException | InterruptedException e) {
System.out.println(e.getMessage());
}
}
}