File的三种构造方法

在E盘Test目录下创建Demo.txt

 

第一个构造函数:

  File(File parent, String child),从父抽象路径名和子路径名字符串创建新的 File实例;

        File filePath = new File("E:"+File.separator+"Test");
        File fs = new File(filePath, "Demo_1.txt");
        fs.createNewFile();

第二个构造函数:

  File(String pathname)通过将给定的路径名字符串转换为抽象路径名来创建新的 File实例;

        File s = new File("E:"+File.separator+"Test"+File.separator+"Demo_2.txt");
        s.createNewFile();

第三个构造函数:

  File(String parent, String child),从父路径名字符串和子路径名字符串创建新的 File实例;

        File ss = new File("E:"+File.separator+"Test", "Demo_3.txt");
        ss.createNewFile();

 

如果E盘下没有Test目录,创建file会报错

Exception in thread "main" java.io.IOException: 系统找不到指定的路径。
	at java.io.WinNTFileSystem.createFileExclusively(Native Method)
	at java.io.File.createNewFile(File.java:883)

解决方法:使用mkdirs();    //创建由此抽象路径名命名的目录,包括任何必需但不存在的父目录

        File filePath = new File("E:"+File.separator+"Test");
        filePath.mkdirs();
        File fs = new File(filePath, "Demo_1.txt");
        fs.createNewFile();

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值