File功能概述

import java.io.*;
/*
File类中常见方法
1,创建
boolean  createNewFile();在指定位置创建文件,如果该文件已经存在,则不创建返回false
和输出流不一样,输出流对象一建立创建文件,而且原存在的会覆盖

boolean mkdir();创建文件夹
boolean mkdirs():创建多级文件夹




2,删除
boolean delete(); 删除失败返回false,如果文件正在被使用,则删除不了
void deleteOnExit(); 在程序退出时删除指定文件。


3,判断
boolean exists();
isFile();
isDirectory();
isHidden();
isAbsolute();


4,获取信息
getName();
getPath();
getParent();


getAbsolutePath();
lastMidified();
length()
*/
class  FileDemo
{
public static void main(String[] args) throws IOException
{
method_5();
//consMethod();

}


public static void method_5()
{
File f1 = new File("c:\\1.jpg");
File f2 = new File("c:\\3.jpg");


sop(f2.renameTo(f1));//重命名,类似于剪切
}


public static void method_3()
{
File f = new File("abc.txt");

//在判断文件对象是否是文件或者目录时,应该要先判断该文件对象封装的内容是否存在
//通过exists
sop("exists:"+f.exists());
sop("dir:"+f.isDirectory());
sop("file:"+f.isFile());


sop(f.isAbsolute());
}

public static void method_2()
{
File f = new File("d.txt");


//sop("exists:"+f.exists());


//sop("execute:"+f.canExecute());

//创建文件夹


File dir = new File("abc.txt/kk/k/kk/k/k");
sop("mkdir:"+dir.mkdirs());
}






public static void method_1() throws IOException
{
File f = new File("file.txt");


//sop("create:"+f.createNewFile());


f.deleteOnExit();//,即使发生异常,退出时也能删除,一般用于临时文件



sop("delete:"+f.delete());
}


public static void method_4()
{
File f = new File("File.txt");


sop("path:"+f.getPath());//文件存不存在都可以
sop("abspath:"+f.getAbsolutePath());//绝对路径
sop("parent:"+f.getParent()); //该方法返回的是绝对路径的父目录(),此处为null
//如果相对路径中有上一层目录,那么该目录就是返回结果
}


public static void consMethod()
{
//将a.txt封装成file对象,可以将已有的和未出现的文件或者文件夹封装成对象
File f1 = new File("c:\\abc\\a.txt");


File f2 = new File("c:\\abc","b.txt");//b可以是变量


File d = new File("c:\\abc");
File f3 = new File(d,"c.txt");


sop("f1:"+f1);
sop("f1:"+f2);
sop("f1:"+f3);
//目录分隔符,实现跨平台
File f4 = new File("c:"+File.separator+"cba/zz"+File.separator+"a.txt");


sop("f4:"+f4);
}


public static void sop(Object obj)
{
System.out.println(obj);
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值