Java基础: File 类的基本使用 -- IO流的基础

前言:

在你写博文的时候,有时候会想上传图片或者相关的文件,比如大佬博客中的图片,都需要上传,上传文件离不开 IO 流,而 IO 流的基础就是对 文件的操作,本篇博文简单介绍一下 File 的基本使用。

文件的创建和删除:

package io;

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

public class Demo01 {

    public static void main(String[] args) {
        File file = new File("d:/a.txt");

        // 判断一个文件是否存在
        boolean flag = file.exists();

        try{
            if(flag) {
//                 删除一个存在的文件
                file.delete();
                System.out.println("删除成功。。。。。。。。");
            } else {
                // 创建一个文件
                file.createNewFile();
                System.out.println("创建成功。。。。。。。。");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}

如何获取文件的相关属性:

package io;

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

public class Demo02 {

    public static void main(String[] args) throws IOException {

        File file = new File("hello.txt");

        if(!file.exists()) {
            file.createNewFile();
        }
        // 获取文件的相对路径,用相对路径时才能在打印时进行区分
        System.out.println(file.getPath());
        // 获取文件的绝对路径
        System.out.println(file.getAbsolutePath());
        // 获取文件名
        System.out.println(file.getName());
        // 文件大小(是以字节为单位的)
        System.out.println(file.length());

    }

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

潘小蓝

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值