MacOS使用Java创建新文件夹的方法

package file;

import org.junit.Test;

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

public class FileCreat {

    public static void main(String[] args) {

    }

    /**
     * @Test注解:
     * JUnit 4发布的新特性之一就是支持了@Test注解;
     * @Test的使用 是该方法可以不用在main方法中调用就可以测试出运行结果的一种测试工具
     * @throws IOException
     */
    @Test
    public void create1() throws IOException {
        //方法1:完整路径
        String filePath1 = "/Users/sabrina/Documents/为新工作冲鸭/test1.xlsx";
        //方法2:父目录文件+子路径
        File parentFile = new File("/Users/sabrina/Documents/为新工作冲鸭/");
        String filePath2 = "test2.xlsx";
        //方法3:父目录文件+子路径
        String parentPath = "/Users/sabrina/Documents/为新工作冲鸭/";
        String filePath3 = "test3.xlsx";

        File myFile1 = new File(filePath1);
        File myFile2 = new File(parentFile,filePath2);
        File myFile3 = new File(parentPath,filePath3);
        try {
            // 创建文件,如果文件已经存在,这个方法会失败
            if (myFile1.createNewFile()) {
                System.out.println("文件创建成功: " + myFile1.getAbsolutePath());
            } else {
                System.out.println("文件已存在,无需创建。");
            }

            // 创建文件,如果文件已经存在,这个方法会失败
            if (myFile2.createNewFile()) {
                System.out.println("文件创建成功: " + myFile2.getAbsolutePath());
            } else {
                System.out.println("文件已存在,无需创建。");
            }

            // 创建文件,如果文件已经存在,这个方法会失败
            if (myFile3.createNewFile()) {
                System.out.println("文件创建成功: " + myFile3.getAbsolutePath());
            } else {
                System.out.println("文件已存在,无需创建。");
            }
        } catch (IOException e) {
            // 异常处理
            System.out.println("创建文件发生错误。"+e.getMessage());
            e.printStackTrace();
        }
    }
}

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值