How do I create Directory/folder?
Once I have tested System.getProperty("user.home");
I have to create a directory (directory name "new folder" ) if and only if new folder does not exist.
new File("/path/directory").mkdirs();
Here "directory" is the name of the directory you want to create/exist.
After ~7 year, I will update it to better approach which is suggested by Bozho.
File theDir = new File("/path/directory");
if (!theDir.exists()){
theDir.mkdirs();
}
With Java 7, you can use Files.createDirectories().
For instance:
Files.createDirectories(Paths.get("/path/to/directory"));
You can try FileUtils#forceMkdir
FileUtils.forceMkdir("/path/directory");
This library have a lot of useful functions.
mkdir vs mkdirs
If you want to create a single directory use mkdir
new File("/path/directory").mkdir();
If you want to create a hierarchy of folder structure use mkdirs
new File("/path/directory").mkdirs();
Create a single directory.
new File("C:\\Directory1").mkdir();
Create a directory named “Directory2 and all its sub-directories “Sub2″ and “Sub-Sub2″ together.
new File("C:\\Directory2\\Sub2\\Sub-Sub2").mkdirs()
Source: this perfect tutorial , you find also an example of use.
For java 7 and up:
Path path = Paths.get("/your/path/string");
Files.createDirectories(path);
It seems unnecessary to check for existence of the dir or file before creating, from createDirectories javadocs:
Creates a directory by creating all nonexistent parent directories first. Unlike the createDirectory method, an exception is not thrown if the directory could not be created because it already exists.
The attrs parameter is optional file-attributes to set atomically when creating the nonexistent directories. Each file attribute is identified by its name. If more than one attribute of the same name is included in the array then all but the last occurrence is ignored.
If this method fails, then it may do so after creating some, but not all, of the parent directories.
The following method should do what you want, just make sure you are checking the return value of mkdir() / mkdirs()
private void createUserDir(final String dirName) throws IOException {
final File homeDir = new File(System.getProperty("user.home"));
final File dir = new File(homeDir, dirName);
if (!dir.exists() && !dir.mkdirs()) {
throw new IOException("Unable to create " + dir.getAbsolutePath();
}
}
Neat and clean:
import java.io.File;
public class RevCreateDirectory {
public void revCreateDirectory() {
//To create single directory/folder
File file = new File("D:\\Directory1");
if (!file.exists()) {
if (file.mkdir()) {
System.out.println("Directory is created!");
} else {
System.out.println("Failed to create directory!");
}
}
//To create multiple directories/folders
File files = new File("D:\\Directory2\\Sub2\\Sub-Sub2");
if (!files.exists()) {
if (files.mkdirs()) {
System.out.println("Multiple directories are created!");
} else {
System.out.println("Failed to create multiple directories!");
}
}
}
}
Though this question has been answered. I would like to put something extra, i.e.
if there is a file exist with the directory name that you are trying to create than it should prompt an error. For future visitors.
public static void makeDir()
{
File directory = new File(" dirname ");
if (directory.exists() && directory.isFile())
{
System.out.println("The dir with name could not be" +
" created as it is a normal file");
}
else
{
try
{
if (!directory.exists())
{
directory.mkdir();
}
String username = System.getProperty("user.name");
String filename = " path/" + username + ".txt"; //extension if you need one
}
catch (IOException e)
{
System.out.println("prompt for error");
}
}
}
Just wanted to point out to everyone calling File.mkdir() or File.mkdirs() to be careful the File object is a directory and not a file. For example if you call mkdirs() for the path /dir1/dir2/file.txt, it will create a folder with the name file.txt which is probably not what you wanted. If you are creating a new file and also want to automatically create parent folders you can do something like this:
File file = new File(filePath);
if (file.getParentFile() != null) {
file.getParentFile().mkdirs();
}
This the way work for me do one single directory or more or them:
need to import java.io.File;
/*enter the code below to add a diectory dir1 or check if exist dir1, if does not, so create it and same with dir2 and dir3 */
File filed = new File("C:\\dir1");
if(!filed.exists()){ if(filed.mkdir()){ System.out.println("directory is created"); }} else{ System.out.println("directory exist"); }
File filel = new File("C:\\dir1\\dir2");
if(!filel.exists()){ if(filel.mkdir()){ System.out.println("directory is created"); }} else{ System.out.println("directory exist"); }
File filet = new File("C:\\dir1\\dir2\\dir3");
if(!filet.exists()){ if(filet.mkdir()){ System.out.println("directory is created"); }} else{ System.out.println("directory exist"); }
if you want to be sure its created then this:
final String path = "target/logs/";
final File logsDir = new File(path);
final boolean logsDirCreated = logsDir.mkdir();
if (!logsDirCreated) {
final boolean logsDirExists = logsDir.exists();
assertThat(logsDirExists).isTrue();
}
beacuse mkDir() returns a boolean, and findbugs will cry for it if you dont use the variable. Also its not nice...
mkDir() returns only true if mkDir() creates it.
If the dir exists, it returns false, so to verify the dir you created, only call exists() if mkDir() return false.
assertThat() will checks the result and fails if exists() returns false. ofc you can use other things to handle the uncreated directory.
This function allows you to create a directory on the user home directory.
private static void createDirectory(final String directoryName) {
final File homeDirectory = new File(System.getProperty("user.home"));
final File newDirectory = new File(homeDirectory, directoryName);
if(!newDirectory.exists()) {
boolean result = newDirectory.mkdir();
if(result) {
System.out.println("The directory is created !");
}
} else {
System.out.println("The directory already exist");
}
}
Here is one attractiveness of the java, using Short Circuit OR '||', testing of the directory's existence along with making the directory for you
public File checkAndMakeTheDirectory() {
File theDirectory = new File("/path/directory");
if (theDirectory.exists() || theDirectory.mkdirs())
System.out.println("The folder has been created or has been already there");
return theDirectory;
}
if the first part of the if is true it does not run the second part and if the first part is false it runs the second part as well
public class Test1 {
public static void main(String[] args)
{
String path = System.getProperty("user.home");
File dir=new File(path+"/new folder");
if(dir.exists()){
System.out.println("A folder with name 'new folder' is already exist in the path "+path);
}else{
dir.mkdir();
}
}
}
Related
How do I create Directory/folder?
Once I have tested System.getProperty("user.home");
I have to create a directory (directory name "new folder" ) if and only if new folder does not exist.
new File("/path/directory").mkdirs();
Here "directory" is the name of the directory you want to create/exist.
After ~7 year, I will update it to better approach which is suggested by Bozho.
File theDir = new File("/path/directory");
if (!theDir.exists()){
theDir.mkdirs();
}
With Java 7, you can use Files.createDirectories().
For instance:
Files.createDirectories(Paths.get("/path/to/directory"));
You can try FileUtils#forceMkdir
FileUtils.forceMkdir("/path/directory");
This library have a lot of useful functions.
mkdir vs mkdirs
If you want to create a single directory use mkdir
new File("/path/directory").mkdir();
If you want to create a hierarchy of folder structure use mkdirs
new File("/path/directory").mkdirs();
Create a single directory.
new File("C:\\Directory1").mkdir();
Create a directory named “Directory2 and all its sub-directories “Sub2″ and “Sub-Sub2″ together.
new File("C:\\Directory2\\Sub2\\Sub-Sub2").mkdirs()
Source: this perfect tutorial , you find also an example of use.
For java 7 and up:
Path path = Paths.get("/your/path/string");
Files.createDirectories(path);
It seems unnecessary to check for existence of the dir or file before creating, from createDirectories javadocs:
Creates a directory by creating all nonexistent parent directories first. Unlike the createDirectory method, an exception is not thrown if the directory could not be created because it already exists.
The attrs parameter is optional file-attributes to set atomically when creating the nonexistent directories. Each file attribute is identified by its name. If more than one attribute of the same name is included in the array then all but the last occurrence is ignored.
If this method fails, then it may do so after creating some, but not all, of the parent directories.
The following method should do what you want, just make sure you are checking the return value of mkdir() / mkdirs()
private void createUserDir(final String dirName) throws IOException {
final File homeDir = new File(System.getProperty("user.home"));
final File dir = new File(homeDir, dirName);
if (!dir.exists() && !dir.mkdirs()) {
throw new IOException("Unable to create " + dir.getAbsolutePath();
}
}
Neat and clean:
import java.io.File;
public class RevCreateDirectory {
public void revCreateDirectory() {
//To create single directory/folder
File file = new File("D:\\Directory1");
if (!file.exists()) {
if (file.mkdir()) {
System.out.println("Directory is created!");
} else {
System.out.println("Failed to create directory!");
}
}
//To create multiple directories/folders
File files = new File("D:\\Directory2\\Sub2\\Sub-Sub2");
if (!files.exists()) {
if (files.mkdirs()) {
System.out.println("Multiple directories are created!");
} else {
System.out.println("Failed to create multiple directories!");
}
}
}
}
Though this question has been answered. I would like to put something extra, i.e.
if there is a file exist with the directory name that you are trying to create than it should prompt an error. For future visitors.
public static void makeDir()
{
File directory = new File(" dirname ");
if (directory.exists() && directory.isFile())
{
System.out.println("The dir with name could not be" +
" created as it is a normal file");
}
else
{
try
{
if (!directory.exists())
{
directory.mkdir();
}
String username = System.getProperty("user.name");
String filename = " path/" + username + ".txt"; //extension if you need one
}
catch (IOException e)
{
System.out.println("prompt for error");
}
}
}
Just wanted to point out to everyone calling File.mkdir() or File.mkdirs() to be careful the File object is a directory and not a file. For example if you call mkdirs() for the path /dir1/dir2/file.txt, it will create a folder with the name file.txt which is probably not what you wanted. If you are creating a new file and also want to automatically create parent folders you can do something like this:
File file = new File(filePath);
if (file.getParentFile() != null) {
file.getParentFile().mkdirs();
}
This the way work for me do one single directory or more or them:
need to import java.io.File;
/*enter the code below to add a diectory dir1 or check if exist dir1, if does not, so create it and same with dir2 and dir3 */
File filed = new File("C:\\dir1");
if(!filed.exists()){ if(filed.mkdir()){ System.out.println("directory is created"); }} else{ System.out.println("directory exist"); }
File filel = new File("C:\\dir1\\dir2");
if(!filel.exists()){ if(filel.mkdir()){ System.out.println("directory is created"); }} else{ System.out.println("directory exist"); }
File filet = new File("C:\\dir1\\dir2\\dir3");
if(!filet.exists()){ if(filet.mkdir()){ System.out.println("directory is created"); }} else{ System.out.println("directory exist"); }
if you want to be sure its created then this:
final String path = "target/logs/";
final File logsDir = new File(path);
final boolean logsDirCreated = logsDir.mkdir();
if (!logsDirCreated) {
final boolean logsDirExists = logsDir.exists();
assertThat(logsDirExists).isTrue();
}
beacuse mkDir() returns a boolean, and findbugs will cry for it if you dont use the variable. Also its not nice...
mkDir() returns only true if mkDir() creates it.
If the dir exists, it returns false, so to verify the dir you created, only call exists() if mkDir() return false.
assertThat() will checks the result and fails if exists() returns false. ofc you can use other things to handle the uncreated directory.
This function allows you to create a directory on the user home directory.
private static void createDirectory(final String directoryName) {
final File homeDirectory = new File(System.getProperty("user.home"));
final File newDirectory = new File(homeDirectory, directoryName);
if(!newDirectory.exists()) {
boolean result = newDirectory.mkdir();
if(result) {
System.out.println("The directory is created !");
}
} else {
System.out.println("The directory already exist");
}
}
Here is one attractiveness of the java, using Short Circuit OR '||', testing of the directory's existence along with making the directory for you
public File checkAndMakeTheDirectory() {
File theDirectory = new File("/path/directory");
if (theDirectory.exists() || theDirectory.mkdirs())
System.out.println("The folder has been created or has been already there");
return theDirectory;
}
if the first part of the if is true it does not run the second part and if the first part is false it runs the second part as well
public class Test1 {
public static void main(String[] args)
{
String path = System.getProperty("user.home");
File dir=new File(path+"/new folder");
if(dir.exists()){
System.out.println("A folder with name 'new folder' is already exist in the path "+path);
}else{
dir.mkdir();
}
}
}
File file = new File("C:\\Users\\user\\Desktop\\new\\"+count);
if (!file.exists()) {
if (file.mkdir()) {
System.out.println("Directory is created!");
} else {
System.out.println("Failed to create directory!");
}
This is my current code for making a folder. As you can see, I am using count (an integer) as my folder name. I have initialized count to zero. Now, I need to increment the counter for new folder, for the dynamic naming of folders, as required for my project. What modification should I do?
A more elegant version(java 8+):
Files.createDirectories(Paths.get("/home/path1/path2/path3"));
The Files.createDirectories creates a new directory; if the parent directories do not exist, they are created as well. The method does not thrown an exception if the directory already exist.
Use recursive method , if Folder already exists this will create new folder using counter
int count;
public void createFolder() {
File file = new File("C:\\Users\\user\\Desktop\\new\\"" + count);
if (!file.exists()) {
if (file.mkdir()) {
System.out.println("Directory is created!");
count++;
}
} else {
System.out.println("Failed to create directory!");
count++;
createFolder();
}
}
I am trying to access a file in remote shared location.
////hostname//data//upload//123//test.txt
File sourceFile=new File("////hostname//data//upload//123//test.txt");
sysout("sourceFile.exists()"+sourceFile.exists())//returning false
If a directory is empty file.exists() is returning true.
I am using Java 1.6
I don't understand what is this weird behavior.
First of all to come back to Erwin´s suggestion, this is not the right attempt. The character \ is used in Java as an escape sequence, usually to print out reserved characters. For example will
String s = "The weather is really "nice" today";
result in an error, as " is already reserved for strings. The correct version would be
String s = "The weather is really \"nice\" today";
Coming back to the question, you have to know that when you create a file and test if it exists Java will validate the abstract pathname of the file. That said, if your abstact path is a directory and it exists true will be returned.
Edit:
If you intend to check if an abstract pathname is a directory try the following:
// Check if a file is a directory
if(file.isDirectory()) {
}
// Check if a file contains something
if(file.list().length > 0) {
}
Check this example ,it checks the directory else creates a new one then your new file created.
File f = new File("D:/image_send");
File file = new File("D:/image_send/" + date + ".txt");
try {
if(!f.isDirectory()){
f.mkdirs();
}
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("File created Success");
public static boolean fileTransfer(String src, String des) throws Exception {
if (des == null || des.equals("") || src == null || src.equals("")) {
return false;
}
File fileExisting = new File(src);
File fileNew = new File(des+ fileExisting.getName());
if (fileExisting.exists() && !fileExisting.isDirectory()) {
if (fileExisting.renameTo(fileNew)) {
System.out.println("File is moved successful!");
} else {
System.out.println("File is failed to move!");
}
}
return fileNew.exists();
}
This is the code for file transfer as per your comment ,use src as sourcepath and des as destination path if you get a boolean false,that means path given is wrong.
So i'm working on a simple Windows Explorer replacement. I want to add the ability to create Folders and Files. For some reason, it only works when i'm in my root or c:/ folder, but as soon as it's somewhere else (for example C:\Program Files (x86)) it doesn't work. I either get a java.io.IOException: Access Denied when i create a File and when i try to create a folder, no Exception comes up, but no folder is created.
This is my code for a new file:
String location = getPath();
String name = JOptionPane.showInputDialog("Fill in the name of the new file. \nDon't forget to add file type (.txt, .pdf).", null);
if(name == null){
}
else {
File newFile = new File(location + "\\" + name);
boolean flag = false;
try {
flag = newFile.createNewFile();
} catch (IOException Io) {
JFrame messageDialog = new JFrame("Error!");
JOptionPane.showMessageDialog(messageDialog, "File creation failed with the following reason: \n" + Io);
}
}
This is my code for a new Folder:
String location = getPath();
String name = JOptionPane.showInputDialog("Fill in the name of the new folder.", null);
if(name == null){
}
else {
File newFolder = new File(location + "\\" + name);
boolean flag = false;
try {
flag = newFolder.mkdir();
} catch (SecurityException Se) {
JFrame messageDialog = new JFrame("Error!");
JOptionPane.showMessageDialog(messageDialog, "Folder creation failed with the following reason: \n" + Se);
}
}
I'm stuck right now and i have no idea what i'm doing wrong to get rid of the access denied error.
Short explenation of how this program works:
My program shows a list of all folders and files from a selected File.
That File is a field in the class JXploreFile called "currentFile", which behaves almost the same as a File.
When browsing through the folders, the currentFile is set to a new JXploreFile, containing the new folder you are in as File.
When creating a new folder/file, my program ask the path the user is currently browsing in with the method getPath().
Thanks for the help!
Image of my program:
Before you try to make any I/O operation just check if you have the permission
go to the parent directory (your case location)
then do something like
File f = new File(location);
if(f.canWrite()) {
/*your full folder creation code here */
} else {
}
try to put
String location ="c:\\user\<<youruser>>\\my documents"
or a folder with full perission to write
When I start my application I create a temp folder:
public static File createTempDir(String name) throws IOException {
File tempDir = File.createTempFile(name, "");
if (!(tempDir.delete())) {
throw new IOException("could not delete" + tempDir.getAbsolutePath());
}
if (!(tempDir.mkdir())) {
throw new IOException("could not create" + tempDir.getAbsolutePath());
}
tempDir.deleteOnExit();
return tempDir;
}
During a session a user might load a file. As a result the old temp dir is deleted and a new is created based on the ID of the file loaded.
During load where the old temp dir is deleted I sometimes get a:
java.io.IOException: Unable to delete file:
Here is how the old temp folder is deleted:
public void cleanup(String tmpPath) {
File tmpFolder = new File(tmpPath);
if (tmpFolder != null && tmpFolder.isDirectory()) {
try {
FileUtils.deleteDirectory(file);
} catch (IOException e) {
e.printStackTrace();
}
}
}
where FileUtils is: org.apache.commons.io.FileUtils. Typically the content of the temp folder is:
mytempfolder_uuid
|-> mysubfolder
|-> myImage.jpg
And the error is:
java.io.IOException: Unable to delete file: C:\Users\xxx\AppData\Local\Temp\mytempfolder_uuid\mysubfolder\myImage.jpg
I have tried to debug the application and before the delete operation is executed verified that the above image is actually located in the specified folder.
The nasty thing is that it only happens sometimes. I have made sure not to have the folder/files in the temp folder open in any other applications. Any ideas/suggestions?
You cannot delete files which are open and you can't delete a directory which contains a file. You have to ensure all files in the directory are closed.
I'd suggest you use the Guava library. It has a method Files.createTempDir() that does exactly what you seem to need:
Atomically creates a new directory somewhere beneath the system's
temporary directory (as defined by the java.io.tmpdir system
property), and returns its name. Use this method instead of
File.createTempFile(String, String) when you wish to create a
directory, not a regular file. A common pitfall is to call
createTempFile, delete the file and create a directory in its place,
but this leads a race condition which can be exploited to create
security vulnerabilities, especially when executable files are to be
written into the directory. This method assumes that the temporary
volume is writable, has free inodes and free blocks, and that it will
not be called thousands of times per second.
try deleting the files in the temp folder before deleting it. Try somethng like
private boolean deleteFolder(File path) {
if (path.exists()) {
File[] files = path.listFiles();
for (File f : files) {
if (f.isDirectory()) {
deleteFolder(f);
} else {
f.delete();
}
}
}
return path.delete();
}
also using deleteOnExit is not a very good idea...
cheers!
public static boolean deleteDir(String path)
{
java.io.File dir = new java.io.File(path);
if (dir.isDirectory())
{
String[] filesList = dir.list();
for(String s : filesList)
{
boolean success = new java.io.File(dir, s).delete();
if(!success)
{
return false;
}
}
}
return dir.delete();
}
and then you can use it like: deleteDir("C:\\MyFolder\\subFolder\\")