Java IO——Files类和Paths

Java的JDK7发生了很大的变化,专门引入了很多类:

import java.nio.file.DirectoryStream;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.FileAttribute;
import java.nio.file.attribute.PosixFilePermission;
import java.nio.file.attribute.PosixFilePermissions;

......等等,来取代原来的基于java.io.File的文件IO操作方式.

public class PathsDemo {

    public static void main(String[] args) {
        // 1)首先是final类Paths的两个static方法,如何从一个路径字符串来构造Path对象:
        Path p1=Paths.get("D:/","a");
        Path p2=Paths.get("D://a//b");
        
        URI uri=URI.create("file:///D://a//c");
        Path p3=Paths.get(uri);
        
        //2)FileSystems构造
        Path p4=FileSystems.getDefault().getPath("D://a//aa.log");
        
        //3)File和Path之间的转换,File和URI之间的转换:
        File file=new File("D://my.txt");
        Path p5=file.toPath();
        URI u=file.toURI();
        System.out.println(p5);
        System.out.println(u);
        
        //4)创建文件
        Path p6=Paths.get("D://a//a.txt");
        try {
            if(!Files.exists(p6)) {
                Files.createFile(p6);
                System.out.println("文件创建成功!");
            }else {
                System.out.println("文件已存在!");
            }
        }catch(Exception e) {
            e.getStackTrace();
        }
        //5)文件写操作
        BufferedWriter bw;
        try {
            bw = Files.newBufferedWriter(Paths.get("D:\\a\\a.txt"), StandardCharsets.UTF_8);
            bw.write("Are you ok?");
            bw.write("I'm fine!");
            bw.flush();
            bw.close();
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        
        
        //6)Files.newBufferedReader读取文件
        try {
            BufferedReader reader=Files.newBufferedReader(Paths.get("D:\\a\\a.txt"),StandardCharsets.UTF_8);
            String str=null;
            while((str=reader.readLine())!=null) {
                System.out.println(str);
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
        // 7)遍历一个文件夹:
        Path dir=Paths.get("D://a");
        try(DirectoryStream<Path> stream=Files.newDirectoryStream(dir)){
            for(Path s:stream) {
                System.out.println(s.getFileName());
            }
        }catch(Exception e) {
            
        }

//7.1)遍历单个目录
        try(Stream<Path> stream=Files.list(Paths.get("D:/"))){
            Iterator<Path> it=stream.iterator();
            while(it.hasNext()) {
                Path p=it.next();
                System.out.println(p.getFileName());
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

// 8)遍历整个文件目录
        Path allDir=Paths.get("C:\\Users\\admin\\eclipse-workspace\\taotao1211");
        List<Path> result=new LinkedList<Path>();
        try {
            Files.walkFileTree(allDir, new FindJavaVisitor(result));
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println("reslut.size()="+result.size());
    }
    
    private static class FindJavaVisitor extends SimpleFileVisitor<Path>{
        private List<Path> result;
        public FindJavaVisitor(List<Path> result) {
            this.result =result;
        }
        
        public FileVisitResult visitFile(Path file,BasicFileAttributes attr) {
            if(file.toString().endsWith(".java")) {
                result.add(file.getFileName());
            }
            
            return FileVisitResult.CONTINUE;
            
        }

    }

}
9)将目录下面所有符合条件的图片删除掉:filePath.matches(".*_[1|2]{1}\\.(?i)(jpg|jpeg|gif|bmp|png)")

public class PathsDemo02 {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        URI uri=URI.create("D://a");
        Path allDir=Paths.get(uri);
        List<Path> result=new LinkedList<Path>();
        try {
            Files.walkFileTree(allDir, new FindJavaVisitor(result));
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println("result.size()"+result.size());
    }
    private static class FindJavaVisitor extends SimpleFileVisitor<Path>{
        private List<Path> result;
        public FindJavaVisitor(List<Path> result) {
            this.result=result;
        }
        public FileVisitResult visitFile(Path file,BasicFileAttributes attrs) {
            String filePath=file.toFile().getAbsolutePath();
            if(filePath.matches(".*_[1|2]{1}\\.(?i)(jpg|jpeg|gif|bmp|png)")) {
                try {
                    Files.deleteIfExists(file);
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                result.add(file.getFileName());
            }
            
            return null;
            
        }
    }

}

转载自:https://blog.csdn.net/u010889616/article/details/52694061

猜你喜欢

转载自blog.csdn.net/yeuteyietir/article/details/81411727