privatestaticvoidTest2(){// 1. 创建文件对象代指某个文件File file =newFile("helloworld-app/src/com/ming/File_/ab.txt");// 2. public boolean exists() 判断当前文件对象,对应的文件路径是否存在,存在返回TrueSystem.out.println(file.exists());// 3. public boolean isFile() 判断当前文件对象指代的是否是文件,是文件返回TrueSystem.out.println(file.isFile());// 4. public boolean isDirectory() 判断是否是文件夹,是文件夹返回TrueSystem.out.println(file.isDirectory());// 5. public String getName() 获取文件名(包含后缀)System.out.println(file.getName());// 6. public long length 获取文件大小,返回字节数System.out.println(file.length());// 7. public long lastModified() 获取文件的最后修改时间System.out.println(file.lastModified());SimpleDateFormat dateFormat =newSimpleDateFormat("yyyy-MM-dd HH:mm:ss");String format = dateFormat.format(file.lastModified());System.out.println(format);// 8. public String getPath() 获取创建文件对象时,使用的路径System.out.println(file.getPath());// 9. public String getAbsolutePath() 获取绝对路径System.out.println(file.getAbsolutePath());// 10、public boolean renameTo(File dest ) 修改文件名boolean b = file.renameTo(newFile("helloworld-app/src/com/ming/File_/abc.txt"));System.out.println(b);}
4 File创建文件、删除文件
方法
说明
public boolean createNewFile()
创建一个新文件(文件内容为空),创建成功返回True
public boolean mkdir()
创建文件夹,注意:只能创建一级文件夹
public boolean mkdirs()
创建文件夹,注意:可以创建多级文件夹
public boolean delete()
删除文件,或者空文件夹,注意:不能删除非空文件夹
privatestaticvoidTest3()throwsIOException{// 1. public boolean createNewFile() 创建一个新文件(文件内容为空),创建成功返回TrueFile file =newFile("helloworld-app/src/com/ming/File_/bdf.txt");
file.createNewFile();// 2. public boolean mkdir() 创建文件夹,注意:只能创建一级文件夹File file2 =newFile("helloworld-app/src/com/ming/File_/aaa");
file2.mkdir();// 3. public boolean mkdirs() 创建文件夹,注意:可以创建多级文件夹File file3 =newFile("helloworld-app/src/com/ming/File_/bbb/ccc/ddd");
file3.mkdirs();// 4. public boolean delete() 删除文件,或者空文件夹,注意:不能删除非空文件夹File file4 =newFile("helloworld-app/src/com/ming/File_/bbb");
file3.delete();}
5 File遍历文件夹
方法
说明
public String[] list()
获取当前目录下所有的"一级文件名称"到一个字符串数组中
public File[] listFiles()
(重点)获取当前目录下所有的"一级文件对象"到一个文件钟祥数组中
privatestaticvoidTest4(){File file =newFile("E:\\repo");// 1. public String[] list() 获取当前目录下所有的"一级文件名称"到一个字符串数组中String[] list = file.list();System.out.println(Arrays.toString(list));// 2. public File[] listFiles() (重点)获取当前目录下所有的"一级文件对象"到一个文件钟祥数组中File[] files = file.listFiles();for(File file1 : files){System.out.println(file1.getPath());}}