Java. Automatic file closure. The statement try with resources. Examples

Automatic file closure. The statement try with resources. Examples


Contents


Search other websites:




 1. Automatically close a file using a try block. The statement try with resources

Any file that is opened and used must be closed by calling the close() method. If this is not done, then it can memory leak and related complications.

JDK 7 introduces a new ability to control file input/output streams – automatic resource management (ARM) or automatic process termination. This feature is based on an improved version of the try statement and consists in preventing cases of erroneous non-closing of a file (not freeing up a resource).

The general form of the try statement, which provides automatic resource management, is as follows:

try (resource_specification) {
  // using of resource
  // ...
}

here resource_specification is an operator that declares and initializes such a resource as an input/output stream to a file. A variable is declared in the resource_specification statement, which is a reference to a managed object. In the case of a file, a variable is declared, which is a reference to a file object.

The above statement is also called a try statement with resources.

Another form of using the try statement with resources is possible. With this specification, a try statement with resources can contain catch and finally blocks.

try (resource_specification) {
  // using a resource
  // ...
}
catch (...) {
  // error processing
  // ...
}
finally {
  // finally block
  // ...
}

 

2. Using the try statement with resources. Converting file contents to an array of strings. Example

The example demonstrates the GetLinesFromFile() function, which converts the contents of a text file into an array of strings of type String[]. The function uses a try statement with resources, in which a file object named fr appears as a resource. There is no call to fr.close() in the try statement. This method will be called automatically.

import java.io.*;

...

// Get file lines as an array of String[]
public static String[] GetLinesFromFile(String filename) throws IOException {
  // Declare internal variables
  String lines[] = null; // array of lines - result
  String lines2[] = null; // additional array of lines
  String s; // additional variable - line
  int symbol;

  // Statement try with resources.
  // A fr file object is created that is associated with the textfile.txt file
  try (FileReader fr = new FileReader(filename)) {
    // Initialization before entering the loop
    lines = new String[0]; // create an array of 0 strings
    s = "";

    // The cycle of reading characters from a file and creating an array of lines[]
    do {
      // Read character from file
      symbol = fr.read();

      if ((char)symbol == '\n') {
        // delete character '\n'
        s = s.substring(0,s.length()-1);

        // add string s to the array of strings lines[]
        lines2 = new String[lines.length+1]; // create a new array lines2[]
        for (int i=0; i<lines.length; i++)
          lines2[i] = lines[i];
        lines2[lines.length] = s;
        lines = lines2;

        // clear the string s
        s = "";
      }
      else {
        s = s + (char)symbol;
      }
    } while (fr.ready());

    // there is no need to close the file,
    // method fr.close() will be called automatically
  }
  catch (FileNotFoundException e) {
    System.out.println("File not found.");
    return null;
  }
  catch (IOException e) {
    System.out.println("I/O error.");
    return null;
  }

  return lines;
}

Using the GetLinesFromFile() method can be, for example, like this

public static void main(String[] args) throws IOException {
  String lines[];
  lines = GetLinesFromFile("textfile.txt");

  if (lines!=null) {
    // Display the array lines[]
    System.out.println("The content of file \"textfile.txt\"");
    for (int i=0; i<lines.length; i++)
      System.out.println(lines[i]);
  }
}

 

3. A try statement with resources that contains multiple file objects. Example

In the try statement, several file objects (resources) can be created simultaneously. In the following example, the CopyTextFiles() function is declared, which implements copying text files.

The function implements a try statement with resources that manages two resources simultaneously. The first fr resource is the file object that is the source (original file). The second resource fw is the file object, which is the receiver or copy.

The function text is as follows.

import java.io.*;

public static void CopyTextFiles(String filename1, String filename2) throws IOException {
  try (FileReader fr = new FileReader(filename1);
       FileWriter fw = new FileWriter(filename2)) {
    int symbol;

    do {
      symbol = fr.read();
      fw.write(symbol);
    } while (fr.ready());

    // No need to call the fr.close () and fw.close () methods,
    // these methods will be called automatically
  }
  catch (IOException e) {
    System.out.println("Error: " + e.getMessage());
    return;
  }
}

A function call from another code can be, for example,

public static void main(String[] args) throws IOException {
  CopyTextFiles("textfile.txt", "textfile3.txt");
}

 


Related topics