【Java-14】关于文件

本文详细介绍了Java中的File类,包括如何创建File对象、获取文件路径、属性以及进行文件操作如重命名、创建和删除。同时,讲解了File类在读写文件中的作用,以及相关的方法如isFile()、isDirectory()等。通过示例代码,展示了File类在实际编程中的应用。
摘要由CSDN通过智能技术生成
package java3;

import org.junit.Test;

import java.io.File;
import java.io.IOException;

/**
 * File类的使用
 *
 * 1.File类的对象代表一个文件或者一个文件目录(俗称文件夹)
 * 2.File声明在java.io包下
 * 3.File(String FilePath);
 *   File(String parentPath,String childPath)
 *   File(File parentFile,String childPath)
 * @author Baobao
 * @create 2021-08-19  22:29
 */
public class FileTest {
    /*
    1.如何创建File类实例

    2.相对路径:相较于某个路径下指明的路径
    绝对路径:包含盘符在内的路径或者文件目录的路径

    3.file类中涉及文件or文件目录的创建,删除,重命名,修改时间,文件大小等方法
    并未涉及写入或者读取文件内容的操作,如果需要读写文件内容,就需要IO流

    4.后续File类的对象常常作为参数传入IO流的构造器中,作为读写的终点
     */
    @Test
    public void test01(){
        File file1=new File("hello.txt");
        System.out.println(file1);
    }

    @Test
    public void test02(){
        File file1=new File("hello.txt");
        System.out.println(file1.getAbsolutePath());
        System.out.println(file1.getPath());
        System.out.println(file1.getName());
        System.out.println(file1.getParentFile());
        System.out.println(file1.length());
        System.out.println(file1.lastModified());
        System.out.println();
    }

    /*
    public boolean renameTo (File dest):把文件重命名为指定的文件路径
    比如:file1.renameTo(file2)为例
    要想返回True,需要file1在硬盘中是存在的,且file2不能在硬盘中存在
     */
    @Test
    public void test03(){

    }
/*
public boolean isDirectory();//判断是否是文件目录
public boolean isFile():判断是否是文件
public boolean exists():判断是否存在
public boolean canRead():判断是否可读
public boolean canWrite():判断是否可写
public boolean isHidden():判断是否可写
 */
    @Test
    public void test04(){
        File file1=new File("hello.txt");
        System.out.println(file1.canRead());
        System.out.println(file1.canWrite());
        System.out.println(file1.isFile());
        System.out.println(file1.isDirectory());
    }
/*
    创建文件对应的功能
 */
    @Test
    public void test05() throws IOException {
        File file1=new File("hi.txt");
        if(!file1.exists()){
            file1.createNewFile();
            System.out.println("创建成功!");
        }else{
            file1.delete();//要想删除成功,路径下不能有文件或者是子目录,需要遍历去删除。
            System.out.println("删除成功");
        }
    }

    @Test
    public void test06(){
        File file1=new File("D:\\JJJJJ\\body");
        boolean mkdir = file1.mkdir();
        if(mkdir){
            System.out.println("创建成功");
        }
        /*
        如果当前文件目录的上层目录不存在,mkdirs可以帮忙创建,而mkdir不会。
         */
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值