栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 前沿技术 > 大数据 > 大数据系统

java中File类的使用

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);

        

        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();
        }
        
    }

}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/712061.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号