Updated March 28, 2023
Introduction to Java Directories
A file system structure containing files and other directories is called directories in java, which are being operated by the static methods in the java.nio.file.files class along with other types of files, and a new directory is created in java using Files.CreateDirectories while creating the parent directories if they are not present, and to set the permissions to the newly created directories, PossixFilePermissions is used.
Creation of Java Directories
The directories can be created using three methods. They are:
- Files.CreateDirectory
- Files.CreateDirectories
- PosixFilePermissions
Using Files.CreateDirectory
A new can be created by using this method Files.CreateDirectory(). File Already Exists Exception is thrown if there is a file that is already existing.
Example
An example program in java to demonstrate the creation of directories using Files.CreateDirectory()
Code:
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class CreateDir {
public static void main(String[] args) throws IOException {
String Name = "C:\Users\admin\Desktop\newdir";
Path path1 = Paths.get(Name);
if (!Files.exists(path1)) {
Files.createDirectory(path1);
System.out.println("Creation of directory successful");
} else {
System.out.println("A directory with this name already exists");
}
}
}
Output:
Using Files.CreateDirectories
A new can be created by using this method Files.CreateDirectories also create the parent directories if they are not created, and there is no exception thrown by this method if the directory is already existing.
Example
An example program in java to demonstrate the creation of directories using Files.CreateDirectories().
Code:
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class CreateDir {
public static void main(String[] args) throws IOException {
String Name = "C:\Users\admin\Desktop\newdir";
Path path1 = Paths.get(Name);
Files.createDirectories(path1);
}
}
Output:
The output of the above program is as shown in the format below:
A new directory is created using File.createDirectories when the above example is executed.
Using PosixFilePermissions
A new directory can be created along with setting its permissions using the method PosixFilePermissions. The Windows system does not permit the usage of this class.
Example
Code:
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.FileAttribute;
import java.nio.file.attribute.PosixFilePermission;
import java.nio.file.attribute.PosixFilePermissions;
import java.util.Set;
public class CreateDir {
public static void main(String[] args) throws IOException {
String Name = "C:\Users\admin\Desktop\newdir";
Path path1 = Paths.get(Name);
if (!Files.exists(path1)) {
Set<PosixFilePermission>permissions1=PosixFilePermissions.fromString("rwxr--r--");
FileAttribute<Set<PosixFilePermission>>fileAttributes=PosixFilePermissions.asFileAttribute(permissions1);
Files.createDirectory(path1, fileAttributes);
System.out.println("Creation of directory successful");
} else {
System.out.println("A directory with this name already exists");
}
}
}
Output:
Methods of Java Directories
There are five methods using which the list of files and directories contained in a directory can be listed. They are:
1. String[] list[]
An array of a string is returned using this method String[] list[]. The names of all the files and the directories present in the directory are present in the array of strings. When we only need the names of the files and all the directories present in a directory, we use this method.
2. String[] list(FilenameFilter filter)
An array of a string is returned using this method String[] list[Filename Filter filter]. All the files and the directories present in the directory are present in the array of strings. The given filter specifies the files to be filtered. When we want to filter the names of the files and the directories present in a directory, we use this method.
3. File[] listFiles[]
An array of objects of the file is returned using this method File[] listFiles[]. When we want to work with an individual directory or file directory, like checking the size of the file or obtaining the absolute path, we use this method.
4. File[] lisFiles(FilenameFilter filter)
An array of objects of a file is returned using this method File[] lisFiles(Filename Filter filter), but the given filter filters the specified file. We filter the file objects with some filter using this method.
5. File[] listFiles(FileFilter filter)
An array of objects of a file is returned using this method File[] lisFiles(Filename Filter filter) ) but the given filter filters the specified file. We filter the file objects with some filter using this method.
Creation of Temporary Directories
CreateTempDirectory() method is used to create temporary directories in java. This method belongs to the class of Files with the prefix specified, and attributes can be added, but this is optional. The below program demonstrates the creation of a temporary directory in Java.
Code:
private void createDir() throws IOException {
Path temp = Files.createTempDirectory("C:\Users\admin\Desktop\newdir");
Path temp = Files.createTempFile(temp, "C:\Users\admin\Desktop\newdir", ".tmp");
List<String> lines1 = Arrays.asList("Line1", "Line2");
Files.write(temp, lines1, Charset.defaultCharset(), StandardOpenOption.WRITE);
System.out.printf("Content written to the temporary file %s%n", tempFile.toString());
}
Program to demonstrate writing into the file
Code:
String dir = System.getProperty("C:\Users\admin\Desktop\newdir");
String file = "check.txt";
String Path = directory + File.separator + fileName;
// contents are written to the file
try(FileWriter fileWriter = new FileWriter(Path)) {
String Content = "This is a file.";
fileWriter.write(Content);
} catch (IOException e) {
// exceptions are handled
}
// contents are read from the file
try(FileReader fileReader = new FileReader(Path)) {
int cha = fileReader.read();
while(cha != -1) {
System.out.print((char)cha);
cha = fileReader.read();
}
} catch (FileNotFoundException e) {
// exceptions are handled
} catch (IOException e) {
// exceptions are handled
Output:
Advantages
The advantages are as given below:
- A root directory is present for each of the source code in every project or subproject.
- There are no clashes in names using directories.
- The files need not be listed to be compiled. The tools must know root directories in order to do anything.
- The number of resources contained is fewer than in the search engine databases.
- The resources that are chosen can be rated, annotated or categorized by using directories.
- The chances of relevant results being retrieved can be increased by using java directories.
Conclusion
In this tutorial, we understand the concept of directories, the creation of directories in java using different methods, a listing of directories in java, creation of temporary directories, writing into the files in the directories, advantages of directories in java and programming examples to demonstrate the creation of directories in java using different methods, writing into the files in java directories along with their output snapshots.
Recommended Articles
This is a guide to Java Directories. Here we discuss the Introduction and the methods of java directories along with different examples and their code implementation. You may also have a look at the following articles to learn more –