CodeGym /Courses /Java Collections /File, Files, Path

File, Files, Path

Java Collections
Level 1 , Lesson 1
Available

"Hi, Amigo. Long time, no see."

"Hi, Bilaabo. What are you going to talk about?"

"Today I'm going to tell you about working with files. Java has a special class (File) that you can use to manage files on a hard drive. For managing file contents, there are other classes: FileInputStream, FileOutputStream, etc."

File, Files, Path - 1

"Interesting. But when you say 'manage files', what do you mean?"

"That just what I'm going to explain now. Files can be created, deleted, renamed, and much more. You can pass a File object to practically every class that works with (reads, writes, changes) the contents of a file. For example:"

You can pass the file name directly to FileInputStream
FileInputStream input = new FileInputStream("c:/path/a.txt");
Or you can create a File object separately, and then pass it to FileInputStrea
File file = new File("c:/path/a.txt");
FileInputStream input = new FileInputStream(file);

"But the second option is longer. I still don't understand why we need these file objects."

"For this specific example, you're right. "This isn't an example of how you have to do it, but rather how you can do it.
But imagine that you need to display a list of all files located in a specific directory. Here's how this can be done using File objects:"

Code
File folder = new File("c:/path/");
for (File file : folder.listFiles())
{
 System.out.println(file.getName());
}

"Is listFiles() a method that returns a list of files in the folder indicated by «c:/path/»?"

"Yes. But programmers usually say 'directory'. The term 'folder' came into use relatively recently, but in principle, both terms are correct and you can say whichever one you prefer."

"OK. And what does getName() do? Return the name of the file? What exactly is included in the name? The full name including the path, or just the name of the file itself?"

"Only the name of the file itself. For the full path, there's file.getAbsolutePath()."

"So what other methods does the File class have?"

"Take a look at this:"

Method Description
boolean isDirectory() Is the File object a directory?
boolean isFile() Is the object a file?
long length() Returns the file size/length in bytes.
boolean createNewFile() Creates a new, empty file if a file with this name does not yet exist.
boolean mkdir() Creates a directory. The name «mkdir» comes from «make directory».
boolean mkdirs() Creates a directory and all its subdirectories.
boolean delete() Deletes the file associated with the object. If the object is a directory, then the directory is deleted only if there are no files in it.
void deleteOnExit() Adds the file to a special list of files that will be automatically deleted when the program exits.
File createTempFile(
String prefix,
String suffix,
File directory)
Creates a temporary file with a randomly generated unique name, something like «dasd4d53sd».
Additional parameters are a name prefix and suffix. If a directory is not specified, then the file is created in a special OS directory for temporary files.
boolean exists() Returns true if a file with the same name exists on the hard drive.
String getAbsolutePath() Returns the full path of the file with all its subdirectories.
String getCanonicalPath() Returns the canonical file path.
For example, converts the path «c:/dir/dir2/../a.txt» to «c:/dir/a.txt»
String[] list() Returns an array of the names of files contained in the directory represented by the current object.
File[] listFiles() Returns an array of files contained in the directory represented by the current File object.
long getTotalSpace() Returns the amount of total space (number of bytes) on the disk on which the file is located.
long getFreeSpace() Returns the amount of free space (number of bytes) on the disk on which the file is located.
boolean renameTo(File) Renames the file, i.e. the contents of the file actually get a new name. In other words, you can rename file «c:/dir/a.txt» to «d:/out/text/b.doc».
String getName() Returns only the file name without the path.
String getParent() Returns only the path (directory) to the current file, without the name itself.
Path toPath() Returns a Path object that corresponds to the current File object.

"Whoa! Not a very small list, huh? And it seems like you can do quite a lot with it: create and delete files, rename them,..."

"So to get the directory of the current file, I need to call getParent()?"

"Yep, but it returns a String ― the file path ― not a File object. Actually, the File class duplicates almost all of its methods: one version returns a String, the other ― a File object. Check it out:"

File file = new File("c:/path/a.txt");
String directory = file.getParent();
File file = new File("c:/path/a.txt");
File directory = file.getParentFile();

If you have a String with the file path and you need a File object, then use the constructor. If the situation is reversed (you have a File object but you need a String), then use getAbsolutePath(). For example:"

String path = "c:/a.txt";
File file = new File(path);
File file = new File("c:/a.txt");
String path = file.getAbsolutePath();

"Got it."

"Great. Then here's a small task for you: show the names of all the files located in the same directory as the current file."

"Nothing could be easier. Here, look:"

Code
//Some file
File originalFile = new File("c:/path/dir2/a.txt");

//An object representing the directory
File folder = originalFile.getParentFile();

//Print the file list on screen
for (File file : folder.listFiles())
{
 System.out.println(file.getName());
}

"Hmm. Correct."

"But it's a little confusing that the same class ― File ― is used for both the file and the directory. That doesn't seem very logical to me."

"It worked out that way for historical reasons. A directory used to be a special 'empty' file on disk. Of course, now a lot has changed, but not everything. That's all I have today."

"Thanks for the interesting lesson, Bilaabo."

Comments (8)
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION
Hoist Level 38, San Diego, United States
26 January 2023
I actually worked at this -- another language for 3 years ?!?! because I was working in Salesforce Cloud for years on Front End and got tired of wondering what was under the Hood in their APEX programming code vs using their cool configuration tools and schema object builders in Flow ? hahahaha
Aldo Luna Bueno Level 1, Peru
14 July 2022
No tenía ni idea de que la clase File también pudiera crear instancias de directorios además de archivos. Una solución elegante.
Gellert Varga Level 23, Szekesfehervar, Hungary
9 January 2022
This is how the f1.renameTo(f2) method works. This method wants to rename the file on disk.

File f1 = new File("C:/someDirectories/someTEXTS/someFile.txt");
File f2 = new File("C:/otherDirectories/otherTEXTS/otherFile.txt");
- if the filename (C:/someDirectories/someTEXTS/someFile.txt) specified in the f1 object exists on disk, - and if the path specified in object f2 (C:/otherDirectories/otherTEXTS) exists on disk, - and if the filename (otherFile.txt) specified in object f2 doesn't exist in that specified directory on disk yet; then f1 file on disk will be renamed to the filename specified in f2 and moved to the directory specified in f2. In this case, it seems as if it were be a moveTo() method:) But: - if the file name specified in the f1 object does not exist on disk, - or if the path specified in object f2 does not exist on disk, - or if the filename specified in object f2 already exists in that directory on disk: it simply will do nothing. It doesn't rename anything, doesn't move anything, what's more it doesn't throw any exceptions. The program normally goes on. But in this case the method returns a boolean false value, so if we pay attention to this returned value, it helps. The method renameTo() never renames the path+filename specified inside object f1. It only renames the file on disk. If you want to rename the filename inside f1 object (but not the file on disk), then you doesn't need to use renameTo(). Just do it this way: f1 = new File("C:/otherFolder/otherFile.xyz");
Jurij Thmsn Level 29, Flensburg, Germany
6 May 2021
from Oracle doc: createNewFile() Atomically creates a new, empty file named by this abstract pathname if and only if a file with this name does not yet exist. getTotalSpace() Returns the size of the partition named by this abstract pathname.
18 August 2020
There is a typo in Methods/Description table for long getTotalSpace()
allthemore Level 41
1 August 2020
There is a typo in the methods table description. Actually "boolean createNewFile()" method returns true if the named file does not exist and was successfully created; false if the named file already exists.
Ewerton Level 30, Belo Horizonte, Brasil
7 July 2019
boolean renameTo(File) : Renames the file, i.e. the contents of the file actually get a new name. In other words, you can rename file «c:/dir/a.txt» to «d:/out/text/b.doc». So, is renameTo a "moveTo" method?
Roy Level 22, Bangkok, Thailand
28 June 2019
Interesting stuff. Please update the getTotalSpace and createNewFile.