Showing posts with label Java IO. Show all posts
Showing posts with label Java IO. Show all posts

Sunday, 30 October 2016

Image Processing (Read and Write) in Java

java.awt.image.BufferedImage
To perform image read and write, the BufferedImage class can be used as holder class. This class is used to store an image in RAM.

javax.imageio.ImageIO
To perform the image read write operation we will import the ImageIO class. This class has static methods to read and write an image.

package amazon.dp;
import java.io.File;
import java.io.IOException;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;

public class ImageReader {

     /**
      * readImage - Method to read an IMAGE
      * @param width
      * @param height
      */
     private static BufferedImage readImage(int width, int height) {

           /** Create an object of BufferedImage with parameter width, height and
            * image int type.TYPE_INT_ARGB represents the Alpha, Red, Green and Blue
            * component of the image pixel using 8 bit integer value. */
           //For storing image in RAM
           BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);


           try {

                File input_file = new File("D:\\Python\\InImage.jpg"); //image file path


                // Reading input file
                image = ImageIO.read(input_file);

                System.out.println("Reading complete.");


           } catch(IOException e) {
                System.out.println("Error: "+e);
           }

           return image;
     }

     /**
      * writeImage - Method to write an IMAGE
      * @param BufferedImage image
      */
     private static void writeImage(BufferedImage image) {
           try {
                // Output file path
                File output_file = new File("D:\\Python\\OuImage.jpg");

                // Writing to file taking type and path as
                ImageIO.write(image, "jpg", output_file);

                System.out.println("Writing complete.");
           } catch(IOException e) {
                System.out.println("Error: "+e);
           }
     }

     public static void main(String args[]) throws IOException {
           int width = 963;    //width of the image
           int height = 640;   //height of the image

           // READ Image
           BufferedImage image = readImage(width,height);

           // WRITE Image
           writeImage(image);
     }
}

Sunday, 23 October 2016

How to get the file last modified date in Java?

In Java, File.lastModified() can be used to get the file’s last modified time stamp.

This method will returns the time in milliseconds (long value), we can format it with SimpleDateFormat to make it readable format.

import java.io.File;
import java.text.SimpleDateFormat;

public class FileLastModifiedDate {
     public static void main(String[] args) {

           File file = new File("C:\\HaxLogs.txt");

           System.out.println("Last modified stamp: " + file.lastModified());

           SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");

           System.out.println("Formatted date: " + sdf.format(file.lastModified()));
     }
}

Tuesday, 28 June 2016

How to Delete a Directory/Folder in Java using Recursion


package com.java.io;

import java.io.File;

/** To delete folders recursively. */
public class DeleteDirectory {

     public static void main(String[] args) {
           String folder = "C:/temp/Dir";

           /** delete directory recursively */
           recurDelete(new File(folder));
     }

     public static void recurDelete(File file) {
           /** recursive loop termination. */
           if (!file.exists()) {
                return;
           }

           /** if directory, go inside and call recursively */
           if (file.isDirectory()) {
                for (File tFile : file.listFiles()) {
                     /** recursive call */
                     recurDelete(tFile);
                }
           }
          
           /** To delete files and empty directory */
           boolean isFileDeleted = file.delete();

           if(isFileDeleted) {
                System.out.println("File deleted: "+file.getAbsolutePath());
           }
     }
}

AutoCloseable and Closeable interface in Java : Since: JDK 1.7

java.lang interface AutoCloseable

Closeable extends AutoCloseable, and is specifically dedicated to IO streams.

Implementing AutoCloseable (or Closeable) allows a class to be used as a resource of the try-with-resources construct introduced in Java 7, which allows closing such resources automatically at the end of a block, without having to add a finally block which closes the resource explicitly.

try(open file or resource here) {
      //...
}
//after try block, file will close automatically.

void close() throws Exception

This method is invoked automatically on objects managed by the try-with-resources statement.

While this interface method is declared to throw Exception, implementer are strongly encouraged to declare concrete implementations of the close method to throw more specific exceptions, or to throw no exception at all if the close operation cannot fail.
Throws: Exception - if this resource cannot be closed.

Example of AutoCloseable

class Resource implements AutoCloseable {
     
      private String value;
     
      public Resource(String value) {
            this.value = value;
      }
     
      @Override
      public void close() throws Exception {
            /* De-reference the unused resource */
            this.value = null;
            System.out.println("Resource closed !!");
      }
     
      public String getValue() {
            return value;
      }
}

public class Demo {
      public static void main(String[] args) {

            try(Resource res =new Resource("Resource opened !!")) {
                  String str = res.getValue();
                  System.out.println(str+"\n");
            } catch (Exception e) {
            }
      }
}
Output:
Resource opened !!
Resource closed !!
Related Posts Plugin for WordPress, Blogger...