Well believe it or not, I have not worked with file Input/Output in Java in almost 4 years now. If you’re in the same boat as me and get to rarely use files, because of the specific problem solving that you’re doing (let’s face it, any small to mid size project fooBarDoAnything() can be worked out in memory, without a database or file usage), then join me and let us write out some good code and become experts (grrr we wish), or rather pro-beginners in working with files in Java.
First off, let me start by asking you – What is a file? According to Wikipedia
A computer file is a resource for storing information, which is available to a computer program and is usually based on some kind of durable storage. A file is “durable” in the sense that it remains available for other programs to use after the program that created it has finished executing. Computer files can be considered as the modern counterpart of paper documents which traditionally are kept in office and library files, and this is the source of the term.
So in cheap words files are durable, meaning they’re saved somewhere outside memory, but at the same time have an expensive I/O overhead.
Now let us take a look at files in Java. We have the File class, but do you know what it entails? A while ago, I got asked in an interview, what is this File? Well the class file is just an abstract representation of a file or directory in Java. It stores a system-independent view of hierarchical pathnames of a file and has a bunch of tools and methods to help us manipulate, create and delete files. To be noted is that when you create a new object File, you create only an abstraction. Not to be confused with the actual creation of a File in you file system, which can be done via .createNewFile() method. For more info check the Java File API
So let us get to our coding quest and start with the most basic operation – creating files or directories. Why don’t you give this a try:
First try at creating a file
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
public static void main(String[] args) throws IOException { String myCoolFileSeparator = System.getProperty("file.separator"); createStarcraftFile(myCoolFileSeparator); } public static void createStarcraftFile(String fileSeparator) throws IOException { File starcraftDump = new File(fileSeparator + "NewDirectoryInTheVoid" + fileSeparator + "ProtossOP"); boolean wasFileCreated = starcraftDump.createNewFile(); if (wasFileCreated) { System.out.println("Hoorah! File Created! My life for aiur"); } else { System.out.println("Oooops, file already exists! Build more pylons"); } } |
- Notes:
- The file separator is unique for different systems! (i.e. Linux has “/” and is different from Windows which has “\”) and that is why it is essential that you use it in your path name instead of a String, say “\”.
- You are using Absolute file names here (which start with a separator), meaning they start absolutely at the root of your system (C:\ for most people using windows). If you were to use new File(“NewDirectoryInTheVoid” + fileSeparator + “ProtossOP”), the file would get created relatively to your project folder instead, meaning your String path argument will get appended to the project’s own pathname. Note how big much of a difference a single separator before an argument can make :O.
So what do you expect this piece of code to do? Create a new file and a new directory in your home folder? Well as it stand it will not. It will throw a java.io.IOException: No such file or directory. Ok So I guess we need a directory to be able to create a file. Let us try again:
Second try at deleting files and dirs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
public static void main(String[] args) throws IOException { String myCoolFileSeparator = System.getProperty("file.separator"); createStarcraftDir(myCoolFileSeparator); createStarcraftFile(myCoolFileSeparator); createStarcraftFile(myCoolFileSeparator); } public static void createStarcraftDir(String fileSeparator) throws IOException { File dirInAiur = new File(fileSeparator + "NewDirectoryInTheVoid"); boolean wasDirCreated = dirInAiur.mkdir(); if (wasDirCreated) { System.out.println("Hoorah! Dir created! My life for aiur"); } } public static void createStarcraftFile(String fileSeparator) throws IOException { File starcraftDump = new File(fileSeparator + "NewDirectoryInTheVoid" + fileSeparator + "ProtossOP"); boolean wasFileCreated = starcraftDump.createNewFile(); if (wasFileCreated) { System.out.println("Hoorah! File Created! My life for aiur"); } else { System.out.println("Oooops, file already exists! Build more pylons"); } } |
So what will happen this time. Ok we will create a dir using mkdir() and then we will create a file using createNewFile(). However on our third call (second try on creating a new file), we will fail to create a new file and will instead print “Oooops, file already exists! Build more pylons”. As it turns out mkdir() and createNewFile() return:
- True: If the file/dir was successfully created
- False: Otherwise
Great! By now you should know how to create files and dirs :). So let us try with a second basic command – deleting a file or dir, which as it turns out, is very similar to creating them:
First try at deleting files
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
public static void main(String[] args) throws IOException { String myCoolFileSeparator = System.getProperty("file.separator"); deleteStarcraftDir(myCoolFileSeparator); deleteStarcraftFile(myCoolFileSeparator); deleteStarcraftDir(myCoolFileSeparator); } public static void deleteStarcraftDir(String fileSeparator) throws IOException { File dirInAiur = new File(fileSeparator + "NewDirectoryInTheVoid"); boolean wasDirDeleted = dirInAiur.delete(); if (wasDirDeleted) { System.out.println("Hoorah! Dir deleted! The power of protoss is overwhelming!"); } else { System.out.println("Oooops! Cannot delete dir! Your warpgate is on cooldown"); } } public static void deleteStarcraftFile(String fileSeparator) throws IOException { File starcraftDump = new File(fileSeparator + "NewDirectoryInTheVoid" + fileSeparator + "ProtossOP"); boolean wasFileDeleted = starcraftDump.delete(); if (wasFileDeleted) { System.out.println("Hoorah! File deleted! The power of protoss is overwhelming!"); } else { System.out.println("Oooops! Cannot delete dir! GG!"); } } |
Once again, you will see that the first time we try to delete() the File object containing the dir, we will fail. This is because the directory was not empty. Note that you need a dir to be empty to be able to delete() it! If you want to delete a whole directory without caring about it’s content you need to do a recursive deletion! Give it a try. Here is the small code I came up with:
Second try at deleting files and dirs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
public static void main(String[] args) throws IOException { String theAbsolutePathToAiur = System.getProperty("file.separator") + "NewDirectoryInTheVoid"; destroyForeverInTheVoid(new File(theAbsolutePathToAiur)); } public static void destroyForeverInTheVoid(File toBeDeleted) { if (toBeDeleted.exists()) { if (toBeDeleted.isDirectory()) { for (File fileInside : toBeDeleted.listFiles()) { destroyForeverInTheVoid(fileInside); } } toBeDeleted.delete(); } } |
There are a few things to note on our newly used methods:
- file.exists() – checks whether a file/dir exists in the system with this files object pathname
- file.isDirectory() – checks if the file with this pathname in the system is a directory
- file.listFiles() – returns an array of abstract pathnames contained in this directory
Well, I meant to write basic I/O file operations too in this post (read, write), but this got a bit long, so I will do that another day.
Hope you guys enjoyed it… And I’ll see you guys next time ;D
Latest posts by Ajk (see all)
- Find Median from Numbers Array - January 1, 2018
- Find Whether a Number Can Be the Sum of Two Squares - August 12, 2017
- How to Find Two Primes Whose Sum is Equal to a Number N - April 22, 2017