File对象
创建file对象
public class Test {
public static void main(String[] args) {
File file1 = new File("E:\\io");
System.out.println(file1);
File file2=new File("E:", "\\io");
System.out.println(file2);
File parent = new File("E:");
File file3 = new File(parent, "\\io");
System.out.println(file3);
File file4 = new File("src\\hello.txt");
System.out.println(file4);
File file5 = new File("D:\\java\\WorkerSpace\\chapter01\\src\\JavaIO\\demo01\\hello.txt");
System.out.println(file5);
File类常用方法
File file = new File("src\\JavaIO\\demo01\\hello.txt");
System.out.println(file.exists());
System.out.println(file.getName());
System.out.println(file.length());
System.out.println(file.getPath());
System.out.println(file.getAbsoluteFile());
System.out.println(file.isFile());
System.out.println(file.isDirectory());
System.out.println(file.delete());
System.out.println(file.createNewFile());
File file2 = File.createTempFile("itcast-", "txt");
file2.deleteOnExit();
System.out.println("是否为文件:"+file2.isFile());
System.out.println("相对路径:"+file2.getAbsoluteFile());
遍历目录下的文件
public static void main(String[] args) {
File file = new File("D:\\python\\WorkSpace\\自学python\\pythonProject19");
String[] names = file.list();
for (String name : names) {
System.out.println(name);
}
System.out.println("=================");
for (String name : names) {
if(name.endsWith(".py"))
System.out.println(name);
}
System.out.println("=================");
FilenameFilter filter = new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
File currentFile = new File(dir, name);
if (currentFile.isFile()&¤tFile.getName().endsWith(".py")){
return true;
}
return false;
}
};
String[] names2 = file.list(filter);
for (String name : names2) {
System.out.println(name);
}
System.out.println("================");
File file2 = new File("D:\\python\\WorkSpace\\自学python");
fileDir(file2);
}
public static void fileDir(File dir){
File[] files = dir.listFiles();
for (File file : files) {
if (file.isDirectory())
fileDir(file);
System.out.println(file.getAbsoluteFile());
}
}
删除文件及目录
public class Test {
public static void main(String[] args) {
File file2 = new File("E:\\io");
deleteDir(file2);
}
public static void deleteDir(File file){
if(file.exists()){
File[] files = file.listFiles();
for (File file1 : files) {
if(file1.isDirectory())
deleteDir(file1);
else{
file1.delete();
}
}
file.delete();
}
}
}