学习-Java输入输出之File类之文件创建删除

任务描述

本关任务:使用 File 类创建目录、生成文件和删除文件。

相关知识

我们知道在 Java 中万物皆对象,所以用来操作文件的也应该是一个对象,它就是 File 类。

如何创建 File 对象(文件对象)

File 对象表示一个文件或者路径,我们可以根据以下方式创建 File 对象:

  • 根据一个路径得到 File 对象;
  • 根据一个目录和一个子文件/目录得到 File 对象。

Java 中路径的两种写法:

  1. // 使用符号\\
  2. C:\\Users\\yy\\Desktop
  3. // 使用符号/
  4. C:/Users/yy/Desktop

创建文件对象示例:

  1. public static void main(String[] args) {
  2. // 通过路径创建文件对象
  3. File file = new File("C:\\Users\\yy\\Desktop");
  4. // 通过路径和子文件创建文件对象
  5. File file1 = new File("C:/Users/yy/Desktop","java.txt");
  6. // 打印文件对象
  7. System.out.println(file);
  8. System.out.print(file1);
  9. }

执行结果:

  1. C:\Users\yy\Desktop
  2. C:\Users\yy\Desktop\java.txt

创建文件

创建文件对象之后,还需使用 createNewFile() 方法才可创建一个文件。

  1. public static void main(String[] args) throws IOException { // 注意异常的抛出
  2. // 创建文件对象
  3. File file = new File("C:/Users/yy/Desktop/y.txt");
  4. // 创建文件
  5. boolean newFile = file.createNewFile();
  6. System.out.print(newFile);
  7. }

执行结果:

  1. true

删除文件

文件对象使用 delete() 方法即可删除文件。

  1. public static void main(String[] args) throws IOException {
  2. // 创建文件对象
  3. File file = new File("C:/Users/yy/Desktop/y.txt");
  4. // 创建文件,创建成功,返回true,创建失败,返回false
  5. boolean newFile = file.createNewFile();
  6. System.out.println(newFile);
  7. // 删除文件,删除成功,返回true,删除失败,返回false
  8. boolean delete = file.delete();
  9. System.out.print(delete);
  10. }

执行结果:

  1. true
  2. true

创建文件夹

文件对象使用 mkdir() 方法即可创建一个文件夹。

  1. public static void main(String[] args) throws IOException {
  2. // 创建文件对象
  3. File file = new File("C:/Users/yy/Desktop/y");
  4. // 创建文件夹,创建成功,返回true,创建失败,返回false
  5. boolean mkdir = file.mkdir();
  6. System.out.print(mkdir);
  7. }

执行结果:

  1. true
import java.io.File;
import java.io.IOException;

public class FileTest {
    public static void main(String[] args) throws IOException {
        // 请在Begin-End间编写完整代码
        /********** Begin **********/
        // 创建目录
        File file = new File("/javatest");
        file.mkdir();
        // 在目录下生成文件
        File file1 = new File("/javatest","a.txt");
        File file2 = new File("/javatest","b.txt");
        file1.createNewFile();
        file2.createNewFile();
        // 删除指定目录下的文件
        File file3 = new File("/test/c.txt");
        file3.delete();
        /********** End **********/
    }
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

摸鱼的三金

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

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

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

打赏作者

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

抵扣说明:

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

余额充值