Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a directory containing a file exist?

Tags:

groovy

I am using groovy to create a file like "../A/B/file.txt". To do this, I have created a service and pass the file path to be created as an argument. This service is then used by a Job. The Job will do the logic in creating the file in the specified directory. I have manually created the "A" directory.

How will I create the "B" directory and the file.txt inside the "A" directory through codes to create it automatically?

I need also to check if directories "B" and "A" exists before creating the file.

like image 902
chemilleX3 Avatar asked Oct 05 '12 01:10

chemilleX3


People also ask

How do you check if files exist in a directory?

To check whether a Path object exists independently of whether is it a file or directory, use my_path. exists() .

How do you check if a file exists in a directory terminal?

In order to check if a file exists in Bash using shorter forms, specify the “-f” option in brackets and append the command that you want to run if it succeeds. [[ -f <file> ]] && echo "This file exists!" [ -f <file> ] && echo "This file exists!" [[ -f /etc/passwd ]] && echo "This file exists!"

How do you check if a directory contains a file in C?

access() Function to Check if a File Exists in C Another way to check if the file exists is to use the access() function. The unistd. h header file has a function access to check if the file exists or not. We can use R_OK for reading permission, W_OK for write permission and X_OK to execute permission.

How do you check if a file exists in a folder Python?

Checking If a Certain File or Directory Exists in Python In Python, you can check whether certain files or directories exist using the isfile() and isdir() methods, respectively. However, if you use isfile() to check if a certain directory exists, the method will return False.


2 Answers

To check if a folder exists or not, you can simply use the exists() method:

// Create a File object representing the folder 'A/B' def folder = new File( 'A/B' )  // If it doesn't exist if( !folder.exists() ) {   // Create all folders up-to and including B   folder.mkdirs() }  // Then, write to file.txt inside B new File( folder, 'file.txt' ).withWriterAppend { w ->   w << "Some text\n" } 
like image 132
tim_yates Avatar answered Oct 21 '22 00:10

tim_yates


EDIT: as of Java8 you'd better use Files class:

Path resultingPath = Files.createDirectories('A/B'); 

I don't know if this ultimately fixes your problem but class File has method mkdirs() which fully creates the path specified by the file.

File f = new File("/A/B/"); f.mkdirs(); 
like image 35
Jack Avatar answered Oct 21 '22 00:10

Jack