Input/Output and Streams in Java
Alex Liu
Software Developer Engineer
File class can represent either a file or a directorymkdir() for directories and createNewFile() for files)
File classimport java.io.File;
File object representing the directoryFile newDirectory = new File("myDirectory");
.mkdir() creates the actual directory on the file systemboolean created = newDirectory.mkdir();
true if the directory is created successfullyfalse if the directory already exists or cannot be created.listFiles() to list files in directory$$
// Creates a `File` object representing the directory `myDirectory`
File dir = new File("myDirectory");
//Retrieves an `array` of `File` objects representing the contents of `myDirectory`
File[] files = dir.listFiles();
array of File objects if the directory existsnull if the directory does not exist// Creates a `File` object for `sample.txt` inside `myDirectory`
File file = new File("myDirectory/sample.txt");
// Retrieves the relative path of the file as a String
String path = file.getPath();
System.out.println(path);
We assume myDirectory already exists; otherwise, file creation or writing will fail
Output:
myDirectory/sample.txt
$$
// Creates a `File` object for `sample.txt` inside `myDirectory`
File file = new File("myDirectory/sample.txt");
// Retrieves the absolute path of the file as a String
String absPath = file.getAbsolutePath();
System.out.println(absPath);
/user/home/myDirectory/sample.txt
Input/Output and Streams in Java