java文件与目录的基本操作(创建,删除,列出)
文件的操作(创建和删除)
public class FileCreateTest {
public static void main(String[] args) {
String path = "d:"+ File.separator+"ajava"+File.separator+"test1.txt";
File f = new File(path);
try {
f.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public class fileDeleteTest {
public static void main(String[] args) {
File f = new File("d:"+File.separator+"ajava"+File.separator+"test1.txt");
if(f.exists()){
f.delete();
}
}
}
目录的相关操作(创建,列出目录中的内容)
public class MkdirCreateTest {
public static void main(String[] args) {
File f = new File("d:"+File.separator+"bjava");
f.mkdir();
}
}
public class FileListOfMkdirTest {
public static void main(String[] args) {
File f = new File("d:"+File.separator);
String[] str = f.list();
for (String s : str) {
System.out.println(s);
}
System.out.println("----------------------------");
File[] files = f.listFiles();
for (File file : files) {
System.out.println(file);
}
}
}
public class AllFilesOfMkdirTest {
public static void main(String[] args) {
File f = new File("d:"+File.separator+"pictures");
print(f);
}
public static void print(File f){
if(f!=null){
if(f.isDirectory()){
File[] files = f.listFiles();
if(files!=null){
for (File file : files) {
print(file);
}
}
}else{
System.out.println(f);
}
}
}
}