public class DirStudy { public static void main(String[] args) { File file = new File("F:/EclipseWorkspace/Java300/temp/test"); //mkdir 父目录中又不存在的就创建失败 若已存在也创建失败 boolean flag = file.mkdir(); System.out.println(flag); //mkdirs 会将文件链中不存在的目录都拿创建 推荐使用mkdirs flag = file.mkdirs(); System.out.println(flag); } }
false
true
File file = new File("F:/EclipseWorkspace/Java300"); //返回该目录下的文件或目录的字符串名称 只返回一层 String[] subString = file.list(); for(String temp:subString) { System.out.println(temp); } File[] subFile = file.listFiles(); for(File temp:subFile) { System.out.println(temp.getPath()); }
.classpath
.project
.settings
bin
src
temp
F:EclipseWorkspaceJava300.classpath
F:EclipseWorkspaceJava300.project
F:EclipseWorkspaceJava300.settings
F:EclipseWorkspaceJava300in
F:EclipseWorkspaceJava300src
F:EclipseWorkspaceJava300 emp
递归打印目录下所有内容:
public static void printPath(File file, int deep) { for (int i = 0; i < deep; i++) { System.out.print("-"); } System.out.println(file.getAbsolutePath()); if (file == null || !file.exists()) { return; } else if (file.isDirectory()) { File[] temp = file.listFiles(); for (File t : temp) { printPath(t, deep + 1); } } }
输出:
F:EclipseWorkspaceJava300 -F:EclipseWorkspaceJava300.classpath -F:EclipseWorkspaceJava300.project -F:EclipseWorkspaceJava300.settings --F:EclipseWorkspaceJava300.settingsorg.eclipse.jdt.core.prefs -F:EclipseWorkspaceJava300in --F:EclipseWorkspaceJava300inioStudy ---F:EclipseWorkspaceJava300inioStudyDirStudy.class ---F:EclipseWorkspaceJava300inioStudyIOstudy1.class --F:EclipseWorkspaceJava300in est ---F:EclipseWorkspaceJava300in eststringTest ----F:EclipseWorkspaceJava300in eststringTestArrayCopy1.class ----F:EclipseWorkspaceJava300in eststringTestMyArrayList.class ----F:EclipseWorkspaceJava300in eststringTestMyHashMap.class ----F:EclipseWorkspaceJava300in eststringTestNode.class ----F:EclipseWorkspaceJava300in eststringTestTestBubbleSort.class ----F:EclipseWorkspaceJava300in eststringTestTestCollection.class ----F:EclipseWorkspaceJava300in eststringTestTestString.class -F:EclipseWorkspaceJava300src --F:EclipseWorkspaceJava300srcioStudy ---F:EclipseWorkspaceJava300srcioStudyDirStudy.java ---F:EclipseWorkspaceJava300srcioStudyIOstudy1.java --F:EclipseWorkspaceJava300src est ---F:EclipseWorkspaceJava300src eststringTest ----F:EclipseWorkspaceJava300src eststringTestArrayCopy1.java ----F:EclipseWorkspaceJava300src eststringTestMyArrayList.java ----F:EclipseWorkspaceJava300src eststringTestMyHashMap.java ----F:EclipseWorkspaceJava300src eststringTestTestBubbleSort.java ----F:EclipseWorkspaceJava300src eststringTestTestCollection.java ----F:EclipseWorkspaceJava300src eststringTestTestString.java -F:EclipseWorkspaceJava300 emp --F:EclipseWorkspaceJava300 emp est
字节到字符是解码(decode),字符到字节是编码(encode)。