文件基础操作
This commit is contained in:
parent
1de9754569
commit
fdaf7334c8
@ -27,5 +27,13 @@ public class Example04 {
|
|||||||
System.out.println(name);
|
System.out.println(name);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (file.exists() && file.isDirectory()) {
|
||||||
|
File[] files = file.listFiles(filter);
|
||||||
|
for (File currentFile : files) {
|
||||||
|
System.out.println(currentFile);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,4 +1,27 @@
|
|||||||
package chapter7;
|
package chapter7;
|
||||||
|
|
||||||
|
import java.io.File;
|
||||||
|
|
||||||
public class Example05 {
|
public class Example05 {
|
||||||
|
public static void main(String[] args) {
|
||||||
|
File file = new File("src");
|
||||||
|
showFiles(file);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 显示指定目录下的所有文件
|
||||||
|
* @param dir 目录
|
||||||
|
*/
|
||||||
|
public static void showFiles(File dir) {
|
||||||
|
// 获取当前目录下所有文件的数组
|
||||||
|
File[] fileArray = dir.listFiles();
|
||||||
|
for (File file : fileArray) {
|
||||||
|
if (file.isDirectory()) {
|
||||||
|
// 如果是目录就递归调用
|
||||||
|
showFiles(file);
|
||||||
|
}
|
||||||
|
// 打印文件的绝对路径
|
||||||
|
System.out.println(file.getAbsolutePath());
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,4 +1,16 @@
|
|||||||
package chapter7;
|
package chapter7;
|
||||||
|
|
||||||
|
import java.io.File;
|
||||||
|
|
||||||
public class Example06 {
|
public class Example06 {
|
||||||
|
public static void main(String[] args) {
|
||||||
|
File file = new File("resources");
|
||||||
|
if (file.exists()) {
|
||||||
|
if (file.delete()) {
|
||||||
|
System.out.println("删除成功!");
|
||||||
|
} else {
|
||||||
|
System.out.println("删除失败!");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,4 +1,32 @@
|
|||||||
package chapter7;
|
package chapter7;
|
||||||
|
|
||||||
|
import java.io.File;
|
||||||
|
|
||||||
public class Example07 {
|
public class Example07 {
|
||||||
|
public static void main(String[] args) {
|
||||||
|
File dir = new File("d:/hello");
|
||||||
|
deleteFiles(dir);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 删除指定目录下的所有文件(包括子目录)
|
||||||
|
* @param dir 目录
|
||||||
|
*/
|
||||||
|
public static void deleteFiles(File dir) {
|
||||||
|
if (dir.exists()) {
|
||||||
|
File[] files = dir.listFiles();
|
||||||
|
// 删除当前目录下的所有文件
|
||||||
|
for (File file : files) {
|
||||||
|
// 如果是目录就递归调用
|
||||||
|
if (file.isDirectory()) {
|
||||||
|
deleteFiles(file);
|
||||||
|
} else {
|
||||||
|
// 如果是文件就删除
|
||||||
|
file.delete();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// 删除当前目录
|
||||||
|
dir.delete();
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
Loading…
x
Reference in New Issue
Block a user