How to work with Files in Java

  1. File
  2. Reading and writing content


File System

File class

  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

  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.


  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.




Software Developer, Java Instructor

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Everything you should know about Python String

A Comprehensive Guide to Managing Web Development Projects

How to Recover Deleted Data in Windows 8/10

Rust? For Creative Coding?

Dear Thortspace … a question about ranking / prioritization

FRANK stories: Agile vs. Waterfall

The Main Misconceptions About SCRUM Methodology

Demystifying Streams in Nodejs

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


Software Developer, Java Instructor

More from Medium

Java Lesson 19: Fun with Dates and Times (in Java)

Java Beginner’s Guide: What it is and why you should learn this programming language

Java - Quick Tips & Tutorials #1

JAVA: Understanding Hibernate