Java IO File类中的知识点

在这里插入图片描述代码

public class Demo3 {

public static void main(String[] args) {
	// TODO Auto-generated method stub
         //test1();	//1.名称
         //test2();	//2.判断信息
         test3();//创建删除文件方法
}
//创建删除文件
public static void test3() {
	//createNewFile()不存在时创建新文件
	String path="d:/QQ/200.jpg";
	//String path="d:/QQ/con";con系统关键字
	File src=new File(path);
	if(!src.exists()) {
		boolean flag;
		try {
			flag = src.createNewFile();
			System.out.println(flag?"成功":"失败");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}	
	}
	//删除文件
 boolean flag=src.delete();
 System.out.println(flag?"成功":"失败");
 // static createTempFile(前缀3个字节长,后缀默认为。temp,默认临时空间
 // static createTempFile(前缀3个字节长,后缀默认,。temp,目录)
	try {
		File temp=File.createTempFile("tes",".temp",new File("d:/QQ"));
     Thread.sleep(10000);
     temp.deleteOnExit();//退出即删除
	} catch (Exception e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
}

//2.判断信息
public static void test2() {
	//String path="1.txt";	
	 //String path="d:/QQ";//文件夹
	//String path="d:/QQ/bg.jpg";绝对路径
	//String path="/QQ/bg.jpg";
	String path="d:/QQ/bg.jpg";//长度
	File src=new File(path);
	//是否存在
	System.out.println("文件是否存在:"+src.exists());
	//是否可写canWrite()  canRead()
	System.out.println("文件是否可写:"+src.canWrite());
	System.out.println("=============");
	//isFile()
	//isDirectory()
	if(src.isFile()) {
		System.out.println("文件");
	}else if(src.isDirectory()){
		System.out.println("文件夹");
	}else {
		System.out.println("文件不存在");
	}
	System.out.println("是否为绝对路径"+src.isAbsolute());
	System.out.println("长度:"+src.length());
	
}

//1.名称
public static void test1() {
	//File src=new File("d:/QQ/bg.jpg");
	//建立联系
	File src=new File("bg.jpg");
	System.out.println(src.getName());//返回名称
	System.out.println(src.getPath());//如果是绝对路径,返回完整路径,否则相对路径
	System.out.println(src.getAbsolutePath());//返回绝对路径
	System.out.println(src.getParent());//返回上一级目录,如果没有上一级,返回null
}

}

猜你喜欢

转载自blog.csdn.net/qq_43615815/article/details/84192321