获取的方法:
常用:
- 获取文件/文件下今昔的方法
String getAbsolutePath() - 获取绝对路径
String getPath() - 获取路径(用什么方式创建对象,就返回什么方式的路径 - 绝对或者是相对)
String getName() - 获取文件或者是文件夹的名字
String getParent() - 返回所在文件夹的路径(根据创建对象时候的路径 - 绝对或者是相对)
File类中可以删除和创建文件(java中删除时不适用window的回收站)
方法:
boolean delete()
boolean createNewFile() - 创建一个文件 - 抛出一个异常IOException
在创建文件的时候,如果文件所在的文件夹不存在,则会报错系统找不到路径,必须确保文件夹存在
boolean mkdir() - 创建文件夹
在创建文件夹的时候,如果文件夹所在的父级文件夹不存在,则会报错系统找不到路径,必须确保父级文件夹存在
boolean mkdirs() - 一次创建多个文件夹
boolean delete()注意点:删除文件夹的时候不能为非空(有东西),否则删除失败!
package Test20_Demo.Demo02;/*@create 2020--12--10--10:27*/import java.io.File;public class FileMethod2 {public static void main(String[] args) {File file = new File("a/b/test.txt");File file2 = new File("D:\\develop\\ideaProject\\untitled\\a\\b\\test.txt");File file3 = new File("a/b");//获取方法演示System.out.println(file.getPath());//相对路径System.out.println(file2.getPath());//绝对路径System.out.println("------------------------------------------------");//将相对路径按照绝对路径的格式打印System.out.println(file.getAbsolutePath());//绝对路径System.out.println(file.getAbsolutePath());//绝对路径System.out.println("------------------------------------------------");System.out.println(file.getName());/*test.txt*/System.out.println(file3.getName());/*b*/System.out.println("------------------------------------------------");System.out.println(file.getParent());/*a\b*/System.out.println(file2.getParent());//绝对路径System.out.println(file3.getParent());/*a*/}}
package Test20_Demo.Demo02;/*@create 2020--12--10--10:27*/import java.io.File;import java.io.IOException;public class FileMethod2 {public static void main(String[] args) throws IOException {//创建对象File file = new File("a/b/test.txt");//删除文件//System.out.println(file.getPath() + ",删除结果" + file.delete());//创建文件//System.out.println(file.getPath() + ",创建结果" + file.createNewFile());//演示创建文件的时候父级文件夹不存在的情况/* File file1 = new File("c/d/test.txt");System.out.println(file.getPath() + ",创建结果" + file.createNewFile());*///创建文件夹 - 要保证父级文件夹已经存在/*File dir = new File("c/d");System.out.println(dir.mkdir());//false*//*File dir = new File("e1/e2");System.out.println(dir.mkdir());*//同时新建多个文件夹File dir = new File("f/g/h/j/k");System.out.println(dir.mkdirs());//删除//这里只是删除了最里面那个文件夹,而且这个文件夹是空的System.out.println(dir.delete());//演示不是空的文件夹能不能删除File ff = new File("a/b");System.out.println(ff.delete());}}
