Press "Enter" to skip to content

How to do Basic operations with Files in Java

Ajk 0

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

    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

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

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

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

The following two tabs change content below.
If you like one of my posts the best way to support is give it a thumbs up, comment, or share it on social media 🙂