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

    }

}

猜你喜欢

转载自blog.csdn.net/qq_43619271/article/details/106300969