Java中的File类
Java.io.File 主要用于文件和目录的创建、查找和删除等操作
路径分割符
File.pathSeparator window 中 路径分隔符为 ; Linux中为 :
File.Separator window 中文件名称分隔符 \ LInux 中为 /
路径
1.路径不区分大小写
2.Java中需要 转义字符 \ \ 表示一个 \
File使用
File f1 = new File("路径或文件");
常用方法
getAbsolutePath( ) 返回此File对象的绝对路径
public class Test {
public static void main(String[] args) {
File f1 = new File("D:\\备份");
String s = f1.getAbsolutePath();
System.out.println(s);
}
}
运行结果:
getPath( ) 将此File转换为路径名字字符串
public class Test {
public static void main(String[] args) {
File f1 = new File("D:\\备份");
String s = f1.getPath();
System.out.println(s);
}
}
运行结果:
getName( ) 返回由此File表示的文件或目录的名称
public class Test {
public static void main(String[] args) {
File f1 = new File("D:\\备份");
String s = f1.getName();
System.out.println(s);
}
}
运行结果:
length() 返回此File表示的文件的长度大小
public class Test {
public static void main(String[] args) {
File f1 = new File("D:\\备份\\copy.txt");
long l = f1.length();
System.out.println(l);
}
}
运行结果:
exists( ) 判断文件或目录是否实际存在
public class Test {
public static void main(String[] args) {
File f1 = new File("D:\\未存在的路径\\no.txt");
boolean b = f1.exists();
System.out.println(b);
}
}
运行结果:
isDirectory( ) 此File表示的是否为一个目录
public class Test {
public static void main(String[] args) {
File f1 = new File("D:\\未存在的路径\\no.txt");
boolean b = f1.isDirectory();
System.out.println(b);
}
}
运行结果:
isFile( ) 判断此File表示的是否为一个文件
public class Test {
public static void main(String[] args) {
File f1 = new File("D:\\备份\\copy.txt");
boolean b = f1.isFile();
System.out.println(b);
}
}
运行结果:
File 类中的创建和删除功能
1.createNewFile( ) 判断是否有当前这个文件 如果没有则创建
public class Test {
public static void main(String[] args) throws IOException {
File f1 = new File("D:\\备份\\newFile.txt");
boolean b = f1.createNewFile();
System.out.println(b);
}
}
运行结果:
2.delete( ) 删除文件或目录
public class Test {
public static void main(String[] args) throws IOException {
File f1 = new File("D:\\备份\\newFile.txt");
boolean b = f1.delete();
System.out.println(b);
}
}
运行结果:
3.mkdir( ) 创建单级文件夹
4.mldirs( ) 创建多级文件夹
File类中的遍历目录
1.list( ) 返回一个String数组 表示该File目录下的所有文件或子目录
public class Test {
public static void main(String[] args) throws IOException {
File f1 = new File("D:\\备份");
String[] s = f1.list();
for(String c : s) {
System.out.print(c+" |");
}
}
}
运行结果:
2.listFiles( ) 返回一个File数组
public class Test {
public static void main(String[] args) throws IOException {
File f1 = new File("D:\\备份");
File[] s = f1.listFiles();
for(File c : s) {
System.out.print("| "+c+" ");
}
}
}
运行结果: