java中File类的使用

package IO;

import java.io.File;
import java.io.IOException;
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.StandardCopyOption;
import java.nio.file.StandardOpenOption;

public class PathFilesDemo {
    public static void main(String[] args) {
        File file = new File("D:\\ideaIU\\test\\1.txt");
        //path
        Path p1= Paths.get("D:\\ideaIU\\test","1.txt");
        System.out.println(p1);

        Path p2=file.toPath();
        System.out.println(p2);

        Path p3= FileSystems.getDefault().getPath("D:\\ideaIU\\test","1.txt");
        System.out.println(p3);

        /**
         * Files工具类
         */

        Path p4=Paths.get("D:\\ideaIU\\test","1.txt");
        String info="hhhhhhh";
        //写文件
        try {
            Files.write(p4,info.getBytes(), StandardOpenOption.APPEND);
            System.out.println("写成功");
        } catch (IOException e) {
            e.printStackTrace();
        }

        //读文件
        try {
            byte[] bytes=Files.readAllBytes(p4);
            System.out.println(new String(bytes));
            System.out.println("读取成功");
        } catch (IOException e) {
            e.printStackTrace();
        }
        //复制文件
        try {
            Files.copy(p3,Paths.get("D:\\ideaIU\\test\\q.txt"), StandardCopyOption.REPLACE_EXISTING);
            System.out.println("复制文件成功");
        } catch (IOException e) {
            e.printStackTrace();
        }
        //移动文件
        try {
            Files.move(p3,Paths.get("d:\\"),StandardCopyOption.REPLACE_EXISTING);
            System.out.println("移动文件成功");
        } catch (IOException e) {
            e.printStackTrace();
        }
        //删除文件
        try {
            Files.delete(p3);//static boolean deleteIfExists(Path path)
            System.out.println("删除文件成功");
        } catch (IOException e) {
            e.printStackTrace();
        }
        //创建新目录,除了最后一个部件,其他必须是已存在的
        try {
            Files.createDirectory(Paths.get("D:\\"));
            //Files.createDirectories(path);//创建路径中的中间目录,能创建不存在的中间部件
            System.out.println("创建目录成功");
        } catch (IOException e) {
            e.printStackTrace();
        }
        //创建一个空文件,检查文件存在,如果已存在则抛出异常而检查文件存在是原子性的,
        //因此在此过程中无法执行文件创建操作
        try {
            Files.createFile(Paths.get("d:\\1.txt"));
            System.out.println("创建文件成功");
        } catch (IOException e) {
            e.printStackTrace();
        }
        
    }

}

你可能感兴趣的:(java,java,后端)