常用方法(文件名操作)
获取文件信息
| 方法名称 | 方法作用 | 
|---|---|
| getName() | 文件名称 | 
| getPath() | 赋值路径(绝对\相对) | 
| getAbsolutePath() | 绝对路径 | 
| getParent() | 绝对路径,如果是相对路径返回null | 
获取构建信息
| 方法名称 | 方法作用 | 
|---|---|
| exists() | 存在 | 
| canRead() | 可读 | 
| canWrite() | 可写 | 
| isFile() | 文件,不存在、文件夹均为false | 
| isDirectory() | 文件夹,不存在、文件均为false | 
获取文件长度(字节数)
| 方法名称 | 方法作用 | 
|---|---|
| length() | 长度,文件夹为0 | 
创建删除文件
| 方法名称 | 方法作用 | 
|---|---|
| createNewFile() | 存在或创建失败返回false | 
| delete() | 删除 | 
| static createTempFile(“test”, “.temp”, new File(“D:/”)) | 创建前缀为“test”,后缀“.temp”, D盘根目录下的临时文件 | 
| static createTempFile(“test”, “.temp”) | 创建前缀为“test”,后缀“.temp”, 默认临时空间的临时文件 | 
| deleteOnExit() | 退出时删除 | 
package cn.hxh.io.file;
import java.io.*;
public class Demo03 {
	public static void main(String[] args) throws IOException, InterruptedException {
		test1();//获取文件信息
		System.out.println();
		test2();//获取构建信息
		System.out.println();
		test3();//获取长度(字节数)
		System.out.println();
		test4();//创建、删除文件
		
	}
	public static void test1() {
		//获取文件信息
		File src = new File("E:/xp/test/1.txt");
		System.out.println(src.getName());
		System.out.println(src.getPath());//打印赋值路径(绝对/相对)
		System.out.println(src.getAbsolutePath());//打印绝对路径
		System.out.println(src.getParent());//返回所在目录绝对路径,如果是相对路径,返回null
	}
	public static void test2() {
		File src = new File("D:/官方驱动光盘.iso");
		System.out.println("存在:" + src.exists());//是否存在
		System.out.println("可读:" + src.canRead());//可读
		System.out.println("可写:" + src.canWrite());//可写
		System.out.println("文件:" + src.isFile());//文件,不存在按文件夹处理
		System.out.println("绝对:" + src.isAbsolute());//是否为绝对路径
		if(src.isFile())
			System.out.println("文件");
		else if (src.isDirectory())
			System.out.println("目录");
		else
			System.out.println("不存在");
	}
	public static void test3() {
		File src = new File("D:/官方驱动光盘.iso");
		System.out.println("字节数:" + src.length());//获取长度(字节数),文件夹为0
	}
	public static void test4() throws IOException, InterruptedException {
		String path = "D:/1.txt";
		File src = new File(path);
		boolean flag = src.createNewFile();
		System.out.println(flag ? "成功" : "失败");//存在/创建失败返回false
		flag = src.delete();
		System.out.println(flag ? "成功" : "失败");
		
		File temp =  File.createTempFile("test", ".temp", new File("D:/"));//创建前缀为“test”,后缀“.temp”, D盘根目录下
		temp.deleteOnExit();//退出时删除
		temp =  File.createTempFile("test", ".temp");//创建前缀为“test”,后缀“.temp”, 默认临时空间
		Thread.sleep(5000);//延时5秒退出
		temp.deleteOnExit();//退出时删除
	}
/*
1.txt
E:\xp\test\1.txt
E:\xp\test\1.txt
E:\xp\test
存在:true
可读:true
可写:true
文件:true
绝对:true
文件
字节数:5013733376
成功
成功
*/
}

 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号