1 package com.bjsxt.io.file; 2 3 import java.io.File; 4 import java.io.IOException; 5 6 /** 7 * 常用方法 8 * 9 * 10 */ 11 public class Demo03 { 12 public static void main(String[] args) { 13 // test1(); 14 // test2(); 15 try { 16 test3(); 17 } catch (IOException e) { 18 e.printStackTrace(); 19 System.out.println("文件操作失败"); 20 } catch (InterruptedException e) { 21 // TODO Auto-generated catch block 22 e.printStackTrace(); 23 } 24 } 25 26 //创建删除文件 27 public static void test3() throws IOException, InterruptedException { 28 //createNewFile() 不存在创建新文件 29 // String path = "E:/xp/test/con"; //con系统关键字 会创建失败 30 String path = "E:/xp/test/200.jpg"; 31 File src = new File(path); 32 if(!src.exists()) { 33 boolean flag = src.createNewFile(); 34 System.out.println(flag?"成功":"失败"); 35 } 36 37 //删除文件 38 boolean flag = src.delete(); 39 System.out.println(flag?"成功":"失败"); 40 41 //static createTempFile(前缀3个字节长,后缀默认.temp) 默认临时空间 42 //static createTempFile(前缀3个字节长,后缀默认.temp,目录) 43 File temp = File.createTempFile("tes", ".temp",new File("e:/xp/test")); 44 Thread.sleep(5000); 45 temp.deleteOnExit(); //退出即删除 46 47 } 48 49 //2、判断信息 50 //3、长度length() 51 public static void test2() { 52 // String path = "2.txt"; 53 // String path = "E:/xp/test/2.jpg"; 54 String path = "E:/xp/test/2.jpg"; 55 File src = new File(path); 56 //是否存在 57 System.out.println("文件是否存在:"+src.exists()); 58 //是否可读写 canWrite() canRead() 59 System.out.println("文件是否可写:"+src.canWrite()); 60 61 //isFile() 62 //isDirectory() 63 if(src.isFile()) { 64 System.out.println("文件"); 65 } else if(src.isDirectory()){ 66 //没有真实存在默认为文件夹 67 System.out.println("文件夹"); 68 } else { 69 System.out.println("文件不存在"); 70 } 71 72 System.out.println("是否为绝对路径:"+src.isAbsolute()); 73 System.out.println("长度为:"+src.length()); //字节数 (不能读取文件夹的长度) 74 75 } 76 77 //1、名称 78 public static void test1() { 79 // File src = new File("E:/xp/test/2.jpg"); 80 //建立联系 81 File src = new File("2.txt"); 82 System.out.println(src.getName()); //返回名称 83 System.out.println(src.getPath()); //如果是绝对路径,返回完整路径,否则相对路径 84 System.out.println(src.getAbsolutePath()); //返回绝对路径 85 System.out.println(src.getParent()); //返回上一级目录,如果是相对,返回null 86 } 87 88 89 90 }