Try With Resources in Java

Try With Resources in Java

Try With Resources in Java

 

In this Article i will  step through the code and show you how to implement try with resources  into a Method to Create a new File.

 


package createFile;

import java.io.BufferedOutputStream;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

public class createF {

// Declare 100 length for array filez"
static File[] filez = new File[100];
// Declare 100 length for array "bReaderO"
static BufferedOutputStream[] bReaderO= new BufferedOutputStream[100];
// Initial Value For sizez"
static int sizez =0;
// Initial Value For sizez2"
static int sizez2 =0;
// Where the File is located to be created
static String descz ="C:/Users/User/Desktop/sample.txt";
// Write the text into the File above
static String conten = "Create a Simple File";
// Where the File is located to be created
static String descz2 ="C:/Users/User/Desktop/sample2.txt";
// Write the text into the File above
static String conten2 = "another Simple File";


//File Creation Method Using Try With Resources
// Difference between try and try with Resource
// For Try you need to call the .close stream at Finally
// For Try with Resources you don't need to

public static void createTheFile(String fls ,String content){

// Every time the Function is Called the sizez incremented

sizez = sizez +1;

// Create a new File Instance
filez[sizez] = new File(fls);

// Every time the Function is Called the sizez incremented
sizez2 = sizez2 +1;


try (OutputStream out = new FileOutputStream(fls);
BufferedOutputStream buffered = new BufferedOutputStream(out);) {

// if the file doesn't exists, then create one
if (! filez[sizez].exists()) {
filez[sizez].createNewFile();
}
// Write the Content from the Parameter pass in the Argument
buffered.write(content.getBytes());
} catch (IOException e) {
e.printStackTrace();
}




}

public static void main(String[] args) {

// Call the Method
createTheFile(descz ,conten);

// Call the Method Second Time
createTheFile(descz2 ,conten2);

}

}

 

Results

Two new File named created

1.sample

2.sample2

 

Java Help Center here

Check out

Passing file path as an argument through a Method in Java here

Leave a Reply

Your email address will not be published. Required fields are marked *

3 × 5 =