Problem with creating a directory in Java - java

I am trying to create a directory in Java. I think I have provided correctly all necessary things so that I make the directory, but it is not created. You can see from my code below and the corresponding output that every element from which I compose the path of the new directory should be correct and valid.
It seems, however, that tDir.mkdir(); is not doing anything, and therefore the success variable is always false. I cannot understand why. Thank you in advance.
System.out.println("experimentDir: " + experimentDir);
System.out.println("item.getName(): " + item.getName());
System.out.println("dirName: " + dirName);
String tDirStr = experimentDir + "/" + item.getName() + "All/"
+ dirName + "DataAll";
System.out.println("tDirStr: " + tDirStr);
File tDir = new File(tDirStr);
if (tDir.exists()) {
System.out.println("EXISTS!!!");
} else {
boolean success = tDir.mkdir();
if(success) {
System.out.println("Dir created");
} else {
System.out.println("No dir created!");
}
Output:
experimentDir: /home/Documents/datasets/test-experiments
item.getName(): PosNegReviews
dirName: test
tDirStr: /home/Documents/datasets/test-experiments/PosNegReviewsAll/testDataAll
No dir created!

If you want to create multiple (nested) directories you should use mkdirs() (note the s).

you may be needing to create any parent directory that dont exist. try File.mkdirs().

public class Test1{
public static void main(String[] args)
{
String path="c:\\dir1\\dir2\\dir3\\dir4";
File dir=new File(path);
if(!dir.exists()){
dir.mkdirs();
}
}
}
above code will create dir4 inside C:\dir1\dir2\dir3. If parent folder does not exist, then it will also create.

Related

Deleting specified file

I'm trying to delete files but it isn't working or I'm missing something.
Here is a little test I'm doing:
private void deleteFromDir(String filename) {
String path = "./test/pacientes/" + filename + ".tds";
File f = new File(path);
System.out.println("Abs path " + f.getAbsolutePath());
System.out.println("Exist " + f.exists());
System.out.println("Filename " + f.getName());
System.out.println("Delete " + f.delete());
}
And the system prints:
Abs path C:\Users\XXXX\Documents\PAI\TSoft.\test\pacientes\John Smith.tds
Exist true
Filename John Smith.tds
Delete false
And of course isn't deleting the file, why? How can I make it work?
Perhaps, you do not have the permission to delete this file. You can use the Files.delete() method, which throws an IOException, in case something goes wrong, to see what the real problem is.

Java mkdir will not work

I have this method where I am trying to create a sub directory into the stations folder. All needed directories are made before this method is called. All folders have the normal positions and are not hidden.
private void moveFiles(){
String[] dates = getDates();
//File oldFile = new File("/stations/CurrentFiles/");
File newFile = new File("/stations/" + dates[0].replaceAll("/", "-") + "-" + dates[1].replaceAll("/", "-") + "_" + System.currentTimeMillis() + "/");
if(!newFile.exists()){
if(newFile.mkdir()){
System.out.println(newFile.isHidden());
}else{
System.out.println("error");
System.out.println(newFile.isHidden());
}
}
}
Not understanding what could make it not make the directory.
I would check to make sure you have write permissions for that directory; try newFile.canWrite().

Move one folder from one place to another one

I am trying to move one folder from c:\root to a different place, let's say, directly to the project folder by using the code below. The variable newFolder is declared as class variable and it has been used in another method where user can rename folder to a different name and it holds the name of the folder that I want to move. The variable fileManager is for a new folder where I want to move my folder. When I run this code I always get "Folder " + fileManager.getName() + " is not moved.". So for some reason it skips if condition and goes to else without moving the folder where I want. Can some one show me how to modify my code in order to move one folder from one place to another one?
File fileManager = new File(newFolder.getName());
try{
if(fileManager.renameTo(new File(fileManager.getName()))){
System.out.println("Folder " + fileManager.getName() + " is moved.");
}else{
System.out.println("Folder " + fileManager.getName() + " is not moved.");
}
}catch(Exception ex){
System.out.println("Error - Folder not found!");
}
You need to call renameTo() on the existing file.
Your code currently is trying to rename the new folder (fileManager) to something, but the new folder (probably) does not exist on your filesystem so it returns false because there is nothing to rename.
Actually, I can't see anything that looks like the original file handle anywhere in this code, but you are going to need the original file in order to rename it.
Your code actually does nothing since it just renames a file to itself:
fileManager.renameTo(new File(fileManager.getName())
I am not sure whether this would return true or false if the file exists already on the OS. Does it count as a "successful rename" if you rename a file to itself?
You probably want something that looks more like this (guessing variable names):
oldFileOrFolder.renameTo(fileManager)
I also got rid of the new File constructor since your object already is of type File.
I would use the Files.move method instead, I had no issues with it. Below is an example using a file instead of a folder.
static File fileManager = new File("C:\\template.xls");
public static void main(String[] args) throws IOException {
Path originalPath = Paths.get(fileManager.getPath());
Path newPath = Paths.get(System.getProperty("user.dir")+ "\\template.xls");
if(Files.move(originalPath, newPath , StandardCopyOption.REPLACE_EXISTING) != null){
System.out.println("Folder " + fileManager.getName() + " is moved.");
}else{
System.out.println("Folder " + fileManager.getName() + " is not moved.");
}
}
As suggested by gnomed, you can also fix your issue with the renameTo method by calling it on the original folder/file, which in this case might be 'newFolder' (confusing name) since it looks to be an actual reference to a file. Below is code with the revision.
static File newFolder = new File("C:\\template.xls");
public static void main(String[] args) {
File fileManager = new File(newFolder.getName());
try{
if(newFolder.renameTo(fileManager)){
System.out.println("Folder " + fileManager.getName() + " is moved.");
}else{
System.out.println("Folder " + fileManager.getName() + " is not moved.");
}
}catch(Exception ex){
System.out.println("Error - Folder not found!");
}
}

How to create multiple directories given the folder names

I have a list of files, the names of these files are are made of a classgroup and an id (eg. science_000000001.java)
i am able to get the names of all the files and split them so i am putting the classgroups into one array and the ids in another.. i have it so that the arrays cant have two of the same values.
This is the problem, i want to create a directory with these classgroups and ids, an example:
science_000000001.java would be in science/000000001/science_000000001.java
science_000000002.java would be in science/000000002/science_000000002.java
maths_000000001.java would be in maths/000000001/maths_000000001.java
but i cannot think of a way to loop through the arrays correctly to create the appropriate directories?
Also i am able to create the folders myself, its just getting the correct directories is the problem, does anyone have any ideas?
Given:
String filename = "science_000000001.java";
Then
File fullPathFile = new File(filename.replaceAll("(\\w+)_(\\d+).*", "$1/$2/$0"));
gives you the full path of the file, in this case science/000000001/science_000000001.java
If you want to create the directory, use this:
fullPathFile.getParentFile().mkdirs();
The above answer is really good for creating new files with that naming convention. If you wanted to sort existing files into their relative classgroups and Ids you could use the following code:
public static void main(String[] args) {
String dirPath = "D:\\temp\\";
File dir = new File(dirPath);
// Get Directory Listing
File[] fileList = dir.listFiles();
// Process each file
for(int i=0; i < fileList.length; i++)
{
if(fileList[i].isFile()) {
String fileName = fileList[i].getName();
// Split at the file extension and the classgroup
String[] fileParts = fileName.split("[_\\.]");
System.out.println("One: " + fileParts[0] + ", Two: " + fileParts[1]);
// Check directory exists
File newDir = new File(dirPath + fileParts[0] + "\\" + fileParts[1]);
if(!newDir.exists()) {
// Create directory
if(newDir.mkdirs()) {
System.out.println("Directory Created");
}
}
// Move file into directory
if(fileList[i].renameTo(new File(dirPath + fileParts[0] + "\\" + fileParts[1] + "\\" + fileName))) {
System.out.println("File Moved");
}
}
}
}
Hope that helps.

How to create a directory in Java?

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();
}
}
}

Categories