import java.io.File; import java.io.IOException; public class FileDemo01 { public static void main(String[] args){ //创建一个新文件 String path1 = "d:" + File.separator + "test.txt"; File f1 = new File(path1); try{ f1.createNewFile(); }catch(IOException e){ e.printStackTrace(); } //文件若存在,删除,若不存在,创建。 String path2 = "d:" + File.separator + "test1.txt"; File f2 = new File(path2); if(f2.exists()){ f2.delete(); } else{ System.out.println("The file doesn't exist!"); System.out.println("I can create it!\n"); try{ f2.createNewFile(); }catch(IOException e){ e.printStackTrace(); } } //创建一个文件夹 String path3 = "d:" + File.separator + "wxe"; File f3 = new File(path3); f3.mkdir(); //列出指定目录的全部文件 String path4 = "d:" + File.separator; File f4 = new File(path4); String str[] = f4.list(); for(int i = 0; i < str.length; i++){ System.out.println(str[i]); } System.out.println("\n列出目录下的所有文件(包括路径):"); String path5 = "d:" + File.separator; File f5 = new File(path5); File files[] = f5.listFiles(); for(int i = 0; i < files.length; i++){ System.out.println(files[i]); } //判断一个给定路径是否是目录 String path6 = "d:" + File.separator; File f6 = new File(path6); if(f6.isDirectory()){ System.out.println(f6.getPath() + "路径是目录"); }else{ System.out.println(f6.getPath() + "路径不是目录"); } //列出给定目录以及子目录下的全部文件,使用递归的方式实现 String path7 = "d:" + File.separator; File f7 = new File(path7); print(f7); } public static void print(File file){ if(file != null){ if(file.isDirectory()){ File f[] = file.listFiles(); if(f != null){ for(int i = 0; i < f.length; i++){ print(f[i]); } } }else{ System.out.println(file); } } } }
Java IO之File类
最新推荐文章于 2013-06-13 21:01:04 发布