Java IO 之 File 的创建、重命名与遍历

File表示存储设备上的一个文件或目录,使用方式查看API即可,比较简单

 1 package org.zln.io.file;
 2 
 3 import java.io.File;
 4 
 5 /**
 6  * Created by coolkid on 2015/6/21 0021.
 7  */
 8 public class TestFile {
 9     /*当前程序根路径*/
10     public static final String rootPath = System.getProperty("user.dir");
11     public static void main(String[] args) {
12         //createFile1();
13 //        rename();
14         showFileList(new File(rootPath));
15     }
16 
17     /**
18      * 遍历文件夹
19      * @param file 根目录
20      */
21     private static void showFileList(File file) {
22         if (file.isDirectory()){
23             System.out.println("目录:"+file.getAbsolutePath());
24             File[] files = file.listFiles();
25             for (File file1:files){
26                 showFileList(file1);
27             }
28         }else {
29             System.out.println("文件:"+file.getAbsolutePath());
30         }
31     }
32 
33     /**
34      * 文件的重命名
35      */
36     private static void rename() {
37         String myPath=rootPath+ File.separatorChar+"myFile";
38         File file = new File(myPath);
39         if (!file.exists()){
40             createFile1();
41         }else {
42             File newFile = new File(rootPath+ File.separatorChar+"myFileNew");
43             file.renameTo(newFile);
44             System.out.println(newFile.getAbsolutePath()+"创建成功");
45         }
46 
47     }
48 
49     /**
50      * 文件的创建
51      */
52     private static void createFile1() {
53         String myPath=rootPath+ File.separatorChar+"myFile";
54         File file = new File(myPath);
55         if (!file.exists()){
56             System.out.println(file.getAbsolutePath()+"不存在,创建");
57             if (file.mkdirs()){
58                 System.out.println("创建成功");
59             }else {
60                 System.out.println("创建失败");
61             }
62         }
63     }
64 }
原文地址:https://www.cnblogs.com/sherrykid/p/4591982.html