How to work with Files in Java

  1. File
  2. Reading and writing content


Well, let’s start first with understanding what is it file and file system.

File System


The file is isolated data with a name and unique file path in the file system. The file has a header and content. Inside the header, it will have metadata — data about this file like size, type, how to read, permissions, last modified, etc. The content part will actually have the content of that file. class package(io — input/output) will have most of the classes we will need to know to work with files in java. The first class we will take a look at is the File class. It represents files and directories in Java. While creating it we have to pass the file path(basically we need to tell which file or directory it should represent as a java object). We cannot read or write data into this file by using only the File object.

  1. Get metadata(data about data) about our file. For example, the size, last modified, and other useful data.
  2. We can create this file/directory if doesn’t exist(or override if it exists)
  3. We can delete it.
  • The file class represents files and directories.
  • In order to create a File object, we need to path File Path for a file we want to represent as a java object.
  • It has many useful methods to gather information about files/directories.
  • we can create an empty file by using createNewFile() method.
  • it does throw an unchecked exception so we need to handle it by declaring or catching(in this example just declaring).
  • In this example, we are creating our file here: /Users/beknazarsuranchiyev/Desktop/apple.txt
    if Desktop directory wouldn’t exist, the code would fail to create our apple.txt file. So createNewFile() is not able to create underline directories if they don’t exist. We will need to create them separately.
  • mkdir() is a method to create a directory(taking name from Linux)
  • if a directory is not created it will not throw an exception but will return false(one reason folder cannot be created is permissions)
  • There is mkdirs() that can create non-existing parent directories.
  • We can find out read access by carRead() method.
  • We can find out write access by canWrite() method.
  • We can find out the execute access by canExecute() method.
  1. Find out which ID is running the code: System.out.println(System.getProperty(""));
  2. If you need more info about files/directories permissions, you might try to run Linux commands from Java code. This is the last option to go.

Reading and writing content

In general, there are two ways of working with reading and writing files in Java.

  1. InputStream and OutputStream.
    The Stream classes are used for inputting and outputting all types of binary or byte data.
  2. Reader and Writer.
    The Reader and Writer classes are used for inputting and outputting characters and strings. Basically, text files.
From OCP Book
  • It will print Hello, World! if my file under /Users/beknazarsuranchiyev/Desktop/test.txt will have Hello, World! content.
  • while((b = != -1) {content.append((char)b);} this is the most important part of the code. will read the piece of the content and return it as int. When it is used next time, it will read the next piece and so on. When it will return -1 it means it reached the end of the file content. First, we are assigning the value of method to our b variable then we are checking if it’s -1 or not. If it’s -1 , we are exiting from the loop and if it’s not we are putting value into our SpringBuilder.
  • We always need to close our resources(files, database connections). In this case, we are closing it in finally block because it always runs(does not matter if an exception occurs or not). in.close() also throws checked exception so we are handling it there as well.
  • In this example, we are reading each byte separately, but there is an option to read multiple bytes at the same time. Reading multiple bytes at the same time of text files requires some extra code to convert bytes into String representation(better to use reader/writer classes).
  • The above code is a little old version of using exceptions and closing. We will see a better way of doing it.
  • try() {} try with resources. The main idea is that it will close the resources automatically in the end so we don’t have to use finally block and close them manually. You can see, we opened two resources there and we don’t have to worry about closing them. The try with resources will handle it. If you want to create your custom class that will work with it, you will need to implement Closeable interface.
  • byte[] buffer = new byte[1024]; we are passing it into read() method. We are specifying the number of bytes to read as one piece. It will improve the efficiency of overall reading and writing.
  • The last thing to note is the way we write into the file. new FileOutputStream(targetFile) is responsible to write content into the file(if the file does not exist it will create one). out.write(buffer, 0, b); is used to write content into the file.
  • 'Inputs' is for reading and 'Outputs' is for writing.
  • As you can see it has a similar concept with Streams.
  • You can see as new BufferedReader(new FileReader(file)) is wrapping low-level reader. This is the way we use high-level IO classes by wrapping the low-level IO classes.
  • in this example, we have a method that will read text file content and return it as String.
  • Notice, we have used stream (not IO streams) of java here to make code shorter.


We use File class to represent files and directories in java. We can get information about this file. We can create new files/directories or we can delete them. However, we cannot use it to read or write content.

  1. Input/Output streams. They read and write all types of data. It works at the binary level.
  2. Readers/Writers. They work for text content files.



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store