A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

11. 目录和文件操作Java代码 1.    // 获取文件信息  2.    exists(): 如 果文件存在,返回true  3.    getCanonicalPath(): 获 取全名  4.    getName(): 文件名  5.    getParent(): 父 目录  6.    canRead(): 如果文件可读,返回true  7.    canWrite(): 如 果文件可写,返回true  8.    lastModified(): 文 件更新时间  9.    length(): 文件大小  10.    isFile(): 如 果是文件,返回true  11.    ifDirectory(): 如 果是目录,返回true  12.    要 调用文件的这些方法,必须  13.    File f = new File(fileName);  14.      15.    // 创建文件  16.    File f = new File("c:\\test\\mytest.txt");  17.    f.createNewFile();  // 创建mytest.txt文件到test目录下  18.      19.    // 修改文件名  20.    File f = new File("c:\\test\\mytest.txt");  21.    f.renameTo(new File("c:\\test\\google.txt"));  22.    把 mytest.txt修改成google.txt  23.      24.    // 删除文件  25.    File f = new File("c:\\test\\mytest.txt");  26.    f.delete();  27.      28.    // 临时文件  29.    File f = new File("C:\\test");  // 指定一个文件夹  30.    // 在test文件夹中创建foo前缀,tmp后缀的临时文件  31.    File tmp = File.createTempFile("foo", "tmp", f);   32.    tmp.deleteOnExit();  // 在程序结束时删除该临时文件  33.      34.    // 更改文件属性  35.    setReadOnly(): 设 置为只读  36.    setlastModified(): 设置最后更改时间  37.      38.    // 列出当前文件夹的文件列表  39.    String[] dir = new java.io.File(".").list();  40.    java.util.Arrays.sort(dir);  41.    for (int i = 0; i < dir.length; i++) {  42.        System.out.println(dir);  43.    }  44.      45.    // 过滤文件列表  46.    class OnlyJava implements FilenameFilter {  47.        public boolean accept(File dir, String s) {  48.            if (s.endsWith(".java") || s.endsWith(".class") || s.endsWith(".jar"))  49.                return true;  50.        }  51.    }  52.      53.    // 获取根目录  54.    File[] rootDir = File.listRoots();  55.    for (int i = 0; i < rootDir.length; i++) {  56.        System.out.println(rootDir);  57.    }  58.      59.    // 创建新目录  60.    new File("/home/ian/bin").mkdir();  // 如果"/home/ian"存在,则可以创建bin目录  61.    new File("/home/ian/bin").mkdirs();  // 如果"/home/ian"不存在,会创建所有的目录  

0 个回复

您需要登录后才可以回帖 登录 | 加入黑马