File类的介绍:
File类构造方法:
常用的有三种:
1 、File(String pathname):通过路径名创建一个新 File 实例。
2、File(File parent, String child):根据父目录路径File实例和子目录或文件路径创建一个新 File 实例。
3、File(String parent, String child) :根据父目录路径和子目录或文件路径创建一个新 File 实例。
public class FileDemo1 {
public static void main(String[] args) throws IOException {
// 1 File(String pathname) 通过将给定的路径名字符串转换为抽象路径名来创建新的File实例
File f1 = new File("F:\\a.txt");
System.out.println(f1); // F:\a.txt
// 2 File(String parent, String child) 父路径名字符串 和 子路径名字符串
File f2 = new File("F:\\abc", "a.txt");
System.out.println(f2); // F:\abc\a.txt
// 3 File(File parent, String child) 父抽象路径名 和 子路径字符串
File f3 = new File(new File("F:\\abc\\a"), "a.txt");
System.out.println(f3); // F:\abc\a\a.txt
/*错误示范:File类构造函数的本质就是将两个字符串连接起来,不会检验路径是否正确*/
File f4 = new File(new File("F:\\abc\\x.jpg"), "aa.txt");
System.out.println(f4); // F:\abc\x.jpg\aa.txt
}
}
其中的正常方法使用:
getAbsolutePath():获取绝对路径
public class FileTest2 {
public static void main(String[] args) {
File f1=new File("D:/aa/hello.txt");//创建了 文件 映射对象
String absolutePath1 = f1.getAbsolutePath();
System.out.println("文件的绝对路径"+absolutePath1);//绝对磁盘路径
}
}
getName():返回此对象表示的文件或目录最后一级文件夹名称
public class FileTest2 {
public static void main(String[] args) {
File f1=new File("D:/aa/hello.txt");//创建了 文件 映射对象
String name1 = f1.getName();//获取文件名,即你定位的元素
System.out.println("文件名称:"+name1);
}
}
getPath(): 返回File对象所表示的字符串路径
public class FileTest2 {
public static void main(String[] args) {
File f1=new File("D:/aa/hello.txt");//创建了 文件 映射对象
String path1 = f1.getPath();
System.out.println("文件的路径"+path1);
}
}
exists(): 判断文件/文件夹是否存在
public class FileTest2 {
public static void main(String[] args) {
File f1=new File("D:/aa/hello.txt");//创建了 文件 映射对象
System.out.println(f1.exists());
}
}
isDirectory(): 判断此File对象代表的路径表示是不是文件夹,只有File对象代表路径存在且是一个目录时才返回true,否则返回false
public class FileTest2 {
public static void main(String[] args) {
File f1=new File("D:/aa/hello.txt");//创建了 文件 映射对象
System.out.println(f1.isDirectory());
}
}