File类 基础知识点

xiaoxiao2021-02-28  44

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();//退出即删除 } }
转载请注明原文地址: https://www.6miu.com/read-81663.html

最新回复(0)