IO,File对象-构造函数和常用方法
程序员文章站
2022-05-07 19:09:50
1 import java.io.File; 2 import java.text.DateFormat; 3 import java.util.Date; 4 5 public class FileDemo { 6 public static void main(String[] args) th... ......
1 import java.io.File; 2 import java.text.DateFormat; 3 import java.util.Date; 4 5 public class FileDemo { 6 public static void main(String[] args) throws Exception{ 7 creatAndDelect(); 8 getDemo(); 9 isDmeo(); 10 reNameToName(); 11 listDemo(); 12 listRootDmeo(); 13 } 14 // 1, 获取 15 public static void getDemo() { 16 // 文件或文件夹名称 17 File file = new File("D:/1.txt"); 18 // 绝对路劲 19 String name = file.getName(); 20 System.out.println(name); 21 // 相对路径 22 String absolutePath = file.getAbsolutePath(); 23 System.out.println(absolutePath); 24 // 文件大小 25 long len = file.length(); 26 System.out.println(len); 27 // 最后一次修改时间 28 long time = file.lastModified(); 29 Date date = new Date(time); 30 DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL); 31 String str_time = dateFormat.format(date); 32 System.out.println(str_time); 33 } 34 // 2, 创建和删除 35 public static void creatAndDelect() throws Exception{ 36 File file = new File("D:\\2.txt"); 37 boolean b = file.mkdirs(); 38 System.out.println(b); 39 System.out.println(file.delete()); 40 //文件 41 // File file2 = new File("D:\\3.txt"); 42 // boolean b1 = file2.createNewFile(); 43 // boolean b2 = file2.delete(); 44 // System.out.println(b1); 45 // System.out.println(b2); 46 } 47 // 3, 判断 48 public static void isDmeo() { 49 File file = new File("D:\\1.txt"); 50 //存在 51 System.out.println("exists:" + file.exists()); 52 //目录 53 System.out.println("isDirectory:" + file.isDirectory()); 54 //文件 55 System.out.println("isFile:" + file.isFile()); 56 //隐藏 57 System.out.println("isHidden:" + file.isHidden()); 58 } 59 // 4, 重命名 60 public static void reNameToName() { 61 File file = new File("D:\\1.txt"); 62 File f = new File("D:\\4.txt"); 63 System.out.println(file.renameTo(f)); 64 } 65 // 5, 系统根目录和容量获取 66 public static void listRootDmeo() { 67 File file[] = File.listRoots(); 68 for(File f : file) { 69 System.out.println(f); 70 System.out.println("FreeSpace:" + f.getFreeSpace()); 71 System.out.println("TotalSpace:" + f.getTotalSpace()); 72 System.out.println("UsableSpace:" + f.getUsableSpace()); 73 } 74 } 75 76 public static void listDemo() { 77 File file = new File("C:\\"); 78 String names[] = file.list(); 79 for(String name : names) { 80 System.out.println(name); 81 } 82 } 83 }
下一篇: OpenGL ES 渲染立体图形