java-I/O File类(1)-createNewFile()-mkdir()-跨平台的绝对路径-delete()-list()-deleteOnExit()


File类


创建一个文件 ,一个File类的对象,表示了磁盘上的文件或目录。

class FileTest {
    public static void main(String[] args) throws IOException{
        File f = new File("1.txt");
        //创建一个文件
        f.createNewFile();
    }
}

这里写图片描述

在eclipse工程目录下新建一个文件成功


创建一个目录

class FileTest {
    public static void main(String[] args) throws IOException{
        File f = new File("1.txt");
        //f.createNewFile();
        //创建目录
        f.mkdir();
    }
}

结果:
这里写图片描述
创建文件成功


如果想在指定的绝对路径创建文件,在File类构造函数时注意


根据window系统的绝对路径创建文件
注意转义字符

class FileTest {
    public static void main(String[] args) throws IOException{
        //绝对路径创建文件,本意是'\'作为目录的分隔符,在windows系统要在'\'加一个'\'
        File f = new File("D:\\eclipse workplace\\FileTest\\1.txt");
        f.createNewFile();
    }
}

结果在指定路径生成了1.txt文件


问题引出:因为在linux目录分隔符是正斜杠’/’程序移植到linux平台就不会识别目录分隔符了,我们要写一个跨平台的绝对路径,File类提供了与平台无关的方法来对磁盘上的文件或目录进行操作。
这里写图片描述
区别是返回值类型不同


class FileTest {
    public static void main(String[] args) throws IOException{
        //File f = new File("D:\\eclipse workplace\\FileTest\\1.txt");

        //代表盘符根目录
        String strDir = File.separator;
        String strFile = "eclipse workplace" + strDir + "FileTest" + strDir + "1.txt";
        File f = new File(strDir,strFile);
        f.createNewFile();
    }
}

删除文件或者目录
f.delete();
在程序退出时删除文件,用于删除程序运行时的文件
deleteOnExit()
创建临时文件并删除临时文件

class FileTest {
    public static void main(String[] args) throws IOException, InterruptedException{
        File f = File.createTempFile("zfdsfdsd", ".tmp");
        f.deleteOnExit();
        Thread.sleep(3000);
    }
}

列出目录或文件中的所有子文件

class FileTest {
    public static void main(String[] args) throws IOException, InterruptedException{
        String strDir = File.separator;
        //File f = new File("D:\\eclipse workplace\\FileTest\\1.txt");
        String strAdd = "eclipse workplace" + strDir + "FileTest";
        File f = new File(strDir,strAdd);
        f.createNewFile();
        String[] names = f.list();
        for(int i=0;i< names.length;i++){
            System.out.println(names[i]);
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值