您的位置:首页 > 其它

File类 基础知识点

2017-09-01 14:59 92 查看
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();//退出即删除

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  File