How to write to a File with try-with-resource in Java? Example Tutorial

Hello Java programmers and all people learning Java, if you are familiar with try-wit-resource statement then you know that its a great language functionality and tool to open files, sockets, streams, and network connections or any resource which are require closing. Before try-with-resource was introduce in Java 7, Java developers have to manually write try catch finally block to close the connections for both success and failure cases to prevent resource leak but it was also tricky and many programmer make mistakes which actually resulted in resource leaks. One common example of that is running out of file descriptors which is used for both opening file and socket in Java.  

If you have worked with web servers like Tomcat and Weblogic then you may have seen the dreaded java.net.SocketException: Too many files open java.io.IOException  which is a popular case of resource leak. 

I have explained that on my earlier post about right way to close streams in Java, but try-with-resource really makes it easy to use resources like files and sockets in Java as you don't need to manually close them anymore, try-with-resource will take care of it. 

This means you also don't need to write code which can hinder business logic and bloat your codebase.  All in all, this result in better and more cleaner and readable code. 



How to write file using try-with-resource in Java? Example

Here is a code example of writing a file using try-with-resource statement in Java. In this program, I have opened file inside try() statement and as long as Resource implement AutoCloseable interface, try-with-resource functionality in Java will take care of closing it.  

This functionality is also known as ARM or Automatic Resource management in Java and you need minimum JDK 7 to us this language feature, its not available in Java 6 and earlier version.

package dto;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

/**
 * How to write to a file using try-with-resource statement
 * in Java. 
 * 
 * @author java67
 */

public class Helloworld {

    public static void main(String args[]) {

        // Writing to a file using try-with-resource statement in Java
        // This means any resource opened in try statement will be
        // automatically closed by Java. 
        // This is valid for all classes which implements AutoCloseable
        // interface. JDBC 4.1 classes are also retrofitted to implement
        // AutoCloseable so that they can be used with try-with-resource
        // statement in Java. 
        
        try (FileWriter writer = new FileWriter("programming.txt");
             BufferedWriter bwr = new BufferedWriter(writer);) {
            
            bwr.write("Java");
            bwr.write("\n");
            bwr.write("C++");
            bwr.write("\n");
            bwr.write("JavaScript");
            bwr.close();
            System.out.println("succesfully written to a file");
            
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
        
        
    }

}


You can see that how we have opened resource inside try(), it looks like function arguments 

   try (FileWriter writer = new FileWriter("programming.txt");
             BufferedWriter bwr = new BufferedWriter(writer);) {

You can also see that we can open multiple resources as long as they are separated by semi-colon. If you notice, we only have catch block and there is no finally block in the end because we don't really need any code for closing these resources, they will be automatically be closed when the code inside try block is finished.

How to write File with try-with-resource in Java? Example Tutorial



Important points about try with resource functionality in Java:

Here are a couple of worth remembering points about this awesome functionality in Java:

1. This functionality is known as try-with-resource or Automatic resource management, ARM in Java which is obvious because it care of closing resources. 

2. Only requirement for this functionality is that resource must be opened inside try statement and they must implement AutoCloseable interface, without this it will not work. 

3. You can still use finally block with try and catch but its not mandatory.


That's all about how to use try-with-resource statement in Java. This should be now the standard way to open resources in Java which require closing. The basic requirement is that the resource like InputStream, File, or Socket must implement AutoCloseable statement. As long as they do, try-with-resource functionality will close them. 

You can also see that code is now much more cleaner and readable. It's easy to focus on what actually happening on try block rather than wondering whether file is closed properly or not. 


Other Java File Tutorials you may like

  • How to delete a directory with files in Java? (example)
  • How to recursive copy directory in Java? (tutorial)
  • How to check if a file exists in Java? (example)
  • How to copy a non-empty directory in Java? (example)
  • How to create a file and directory in Java? (solution)
  • How to read a ZIP archive in Java? (solution)
  • 2 ways to read a text file in Java? (example)
  • How to append text to an existing file in Java (solution)
  • How to write to file using BufferedWriter in Java? (example)


Thanks for reading this article so far. If you like this Java File tutorial and my advice on using try-with-resources with files and InputStream then please share with your friends and colleagues. IF you have any questions or feedback then please ask in comments, happy to answer and clear you doubts.

No comments:

Post a Comment

Feel free to comment, ask questions if you have any doubt.