java-io流--(三)--java对文件的基础操作

对文件夹的增加
对文件的增加
对文件的删除

代码演示:

package com.example.io;

import java.io.File;
import java.io.IOException;
import java.util.Date;

public class FileTest {

    public static void main(String[] args) {
//        得到文件路径
          FileTest fileTest = new FileTest();
          String path = fileTest.getFilePath();
          path = getPath(path);
//        得到这样的路径:  D:\IDEAALL2\dtest\target\classes\com\example\io\
          System.out.println(path);

//        文件夹的创建
//          先添加一个以前没有的文件夹
        path = path+"testFile01";
        System.out.println(path);
//        得到路径后就可以创建文件夹了:(创建文件夹时,不能有多余的文件,可能会创建失败)
        File file = new File(path);
        if(!file.exists()){
            file.mkdir();
        }

//        文件的创建
        path = path + "\\123.txt";
        file = new File(path);
        if(!(file.exists())){
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        System.out.println("文件名称:" + file.getName());
        System.out.println("文件是否存在:" + file.exists());
        System.out.println("文件的相对路径:" + file.getPath());
        System.out.println("文件的绝对路径:" + file.getAbsolutePath());
        System.out.println("是否为可执行文件:" + file.canExecute());
        System.out.println("文件可以读取:" + file.canRead());
        System.out.println("文件可以写入:" + file.canWrite());
        System.out.println("文件上级路径:" + file.getParent());
        System.out.println("文件大小:" + file.length() + "B");
        System.out.println("文件最后修改时间:" + new Date(file.lastModified()));
        System.out.println("是否文件类型:" + file.isFile());
        System.out.println("是否为文件夹:" + file.isDirectory());


//        文件的删除
        if(!file.exists()){
            System.out.println("文件不存在!");
        }
        boolean isSuccess = file.delete();
        if(isSuccess){
            System.out.println("文件删除成功!");
        }else {
            System.out.println("文件删除失败!");
        }


    }

    public String getFilePath(){

        return this.getClass().getResource("").getPath();

    }

    public static String getPath(String pathIn){

        pathIn = pathIn.substring(1,pathIn.length());
        pathIn = pathIn.replace("/", "\\");
        System.out.println("pathIn==="+pathIn);
        return pathIn;
    }

}

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值