Example of Mkdir
From Java Example Source Code
Contents |
[edit] Overview - Example of Mkdir
This is a java example of making a new directory, with mkdir() or mkdirs().
[edit] Java Source Code
- Package: com.exampleshow.file
- File: MkdirDemo .java
package com.exampleshow.file; /** * @author Code Panda * Copyright (C) 2008 Java ExampleShow (http://java.exampleshow.com) * * This code is free software; you can redistribute it and/or modify it. * However, this header must remain intact and unchanged. Additional * information may be appended after this header. Publications based on * this code must also include an appropriate reference. * * This code is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. * */ import java.io.File; public class MkdirDemo { public void test() { try { String dirPath = "c:/exampleshow"; String subDirPath = "c:/exampleshow/java/file/io"; doMkDir(dirPath, false); doMkDir(dirPath, true); doMkDir(subDirPath, false); doMkDir(subDirPath, true); } catch (Exception e) { e.printStackTrace(); } } public void doMkDir(String dirPath, boolean isMkDirs) throws Exception { System.out.println("\nTry to " + (isMkDirs?"mkdirs":"mkdir") + " " +dirPath + "..."); File dir = new File(dirPath) ; if(dir.exists()) { System.out.println("Exists: " + dir ); } else { boolean flag = (isMkDirs)? dir.mkdirs() : dir.mkdir(); System.out.println( ( isMkDirs?"mkdirs": "mkdir" ) + " "+dir+" -> " + (flag?"success":"failure")); } } public static void main(String[] args) { MkdirDemo demo = new MkdirDemo(); demo.test(); } }
[edit] What Result You Can Get
Run the program, the first time, you will get:
Try to mkdir c:/exampleshow... mkdir c:\exampleshow -> success Try to mkdirs c:/exampleshow... Exists: c:\exampleshow Try to mkdir c:/exampleshow/java/file/io... mkdir c:\exampleshow\java\file\io -> failure Try to mkdirs c:/exampleshow/java/file/io... mkdirs c:\exampleshow\java\file\io -> success
the sencond time, because all the directories are exist, you will get:
Try to mkdir c:/exampleshow... Exists: c:\exampleshow Try to mkdirs c:/exampleshow... Exists: c:\exampleshow Try to mkdir c:/exampleshow/java/file/io... Exists: c:\exampleshow\java\file\io Try to mkdirs c:/exampleshow/java/file/io... Exists: c:\exampleshow\java\file\io
[edit] Required External Library for this Java Example
Need nothing.
[edit] How to Run this Java Example Program
We recommend running this Java example program with Eclipse.
For assistance in working with Eclipse, please see How to Run Java Program with Eclipse.
It's fairly easy.
