File类 基础知识点

package com.taofei.File.Method;


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


public class FileMethod {
public static void main(String[] args) throws IOException, InterruptedException {
test("C:/Users/Administrator/Desktop/001HKLnwty6FHfIKX3t73&690.jpg");
//test01("C:/Users/Administrator/Desktop/taofei.jpg");
//test02("C:/Users/Administrator/Desktop/taofei.jpg");
test03("C:/Users/Administrator/Desktop");
}


/**
* File对象的一些常用方法
* @param src
*/

public static void test(String src) {

File file = new File(src);
System.out.println(file.getName());//获取文件名
System.out.println(file.getPath());//如果是绝对路径 返回绝对路径 反之 返回相对路径
System.out.println(file.getAbsolutePath());//返回绝对路径
System.out.println(file.getParentFile());//返回父路径
System.out.println(file.getParent());//返回上一级目录 如果src是相对路径则返回null
}
/**
* 判断文件的各种信息
*/
public static void test01(String src){
//与目标文件建立联系  这里File对象既可以表示对象也可以表示文件夹
File file= new File(src);
System.out.println("文件是否存在\t"+file.exists());
System.out.println("是否是文件夹\t"+file.isDirectory());
System.out.println("文件是否可执行\t"+file.canExecute());
//注意这里的大小 单位 是 字节 并且只能够读文件的长度 不能够读取文件夹的长度
System.out.println("文件的大小 "+file.length()+"字节");
System.out.println("文件是否可读\t"+file.canRead());
System.out.println("文件是否可写\t"+file.canWrite());
System.out.println("是否为绝对路径 "+file.isAbsolute());
//判断 file是否是文件  如果file不存在默认是文件夹
if(file.isFile()){
System.out.println(file.toString()+"是文件");
}else{
System.out.println(file.toString()+"是文件夹");
}
}

/**创建和删除文件与文件夹
* @param src
* @throws IOException 
*/
public static void test02(String src) throws IOException {
File file=new File(src);
//如果文件不存在 就创建一个新的文件
if(!file.exists()){

boolean flag=file.createNewFile();
System.out.println("文件创建"+(flag?"成功":"失败"));
}
boolean flag=file.delete();
System.out.println("文件删除"+(flag?"成功":"失败"));
}

/**
* 临时文件的创建与删除
* @param src
* @throws IOException 
* @throws InterruptedException 
*/
public static void test03(String src) throws IOException, InterruptedException{
File temp= File.createTempFile("tem", ".temp",new File(src));

Thread.sleep(2000);
temp.deleteOnExit();//退出即删除


}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值