import java.io.IOException;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.StandardCopyOption;
import java.nio.file.StandardOpenOption;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.FileTime;
import java.time.Instant;
public class NioRelateApiTest {
public static void main(String[] args) throws IOException {
// testCopyFileByFileChannel();
// testCopyFileByFiles();
// testDelete(getFilePath("temp"));
// testWite();
// testRead();
}
static void testWrite() throws IOException {
String text = "hello world";
Files.write(getFilePath("abc.txt"),text.getBytes(),StandardOpenOption.APPEND);
}
static void testRead() throws IOException {
System.out.println(new String(Files.readAllBytes(getFilePath("abc.txt")), Charset.forName("utf-8")));
}
static void testDelete(Path path) throws IOException {
if(Files.isDirectory(path)){
Files.walkFileTree(path,new SimpleFileVisitor<Path>(){
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
Files.delete(file);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc)
throws IOException
{
// 如果不排除根目录,会报DirectoryNotEmptyException异常
if(!dir.equals(path)){
Files.delete(dir);
}
return FileVisitResult.CONTINUE;
}
});
// 根目录最后删除
Files.delete(path);
}else{
Files.deleteIfExists(path);
}
}
static void testCopyFileByFiles(){
try {
Files.copy(getFilePath("abc.txt"),getFilePath("efg.txt"), StandardCopyOption.REPLACE_EXISTING);
Files.setLastModifiedTime(getFilePath("efg.txt"), FileTime.from(Instant.now()));
} catch (IOException e) {
e.printStackTrace();
}
}
static void testCopyFileByFileChannel(){
try (
FileChannel srcChannel = FileChannel.open(getFilePath("abc.txt"), StandardOpenOption.READ);
FileChannel targetChannel = FileChannel.open( getFilePath("efg.txt"), StandardOpenOption.TRUNCATE_EXISTING,StandardOpenOption.WRITE);
) {
srcChannel.transferTo(0, srcChannel.size(),targetChannel);
} catch (IOException e) {
e.printStackTrace();
}
}
static Path getFilePath(String fileName){
return Paths.get(fileName);
}
}
Java NIO关于文件读写、拷贝、删除操作备忘
最新推荐文章于 2024-03-19 15:26:18 发布