How to Create, Write/Append, Read, Delete and Rename a file in Java?

 


We can see in all applications and programs we may need to write or edit file. File operations like creating, deleting, append etc., So in this tutorial we will see about Create, Write, Read and Delete a file using Java code. Each file operations we will discuss with separate program and lets see the output. 
NOTE: File name, path and folder names can vary accordingly. 


1. How to create a file in Java?


public class CreateFile {
    public static void main(String[] args) {
        File myFile = new File("javadiscover.txt");
        try{
        if(!(myFile.exists())){ // checking file exist or not
            myFile.createNewFile(); // Creating new file
            System.out.println("New File created....");
        }else{
            System.out.println("File already exisit....");
        }
        }catch (IOException e) {
            e.printStackTrace();
        }
    }
}



OUTPUT:


New File created....




2. How to Write/ Append a text into a file in Java ?

public class WriteFile {
    public static void main(String[] args) {
        
        FileWriter fWrite = null;
        BufferedWriter bWrite = null;
        
        String content = "Hi All, Welcome to Java Discover";
        File myFile = new File("javadiscover.txt");
        
        try{
            if(!(myFile.exists())){
                myFile.createNewFile();
        }
        fWrite = new FileWriter(myFile, true); // true for appending content to the existing file
            bWrite = new BufferedWriter(fWrite);
            bWrite.write(content);
            bWrite.close();
            
            System.out.println("File write complete.....");
            
        }catch (IOException e) {
            e.printStackTrace();
        }finally{
            if(fWrite != null
                try { fWrite.close(); } catch (IOException e) { e.printStackTrace(); }
            if(bWrite != null
                try { bWrite.close(); } catch (IOException e) { e.printStackTrace(); }            
        }
    }
}



OUTPUT:

Console

File write complete.....


File


3. How to read a file in Java ?


public class ReadFile {
    public static void main(String[] args) {
        BufferedReader br = null;
        try{
            FileReader myFile  = new FileReader("javadiscover.txt");
            br = new BufferedReader(myFile);
            String line = null
            while ((line = br.readLine()) != null) {
                System.out.println(line);
            }
        }catch (IOException e) {
            e.printStackTrace();
        }finally{
            if(br != null
                try{ br.close(); }catch(IOException e){e.printStackTrace();}
        }        
    }
}


OUTPUT:


Hi All, Welcome to Java Discover
Blog about Java questions and answers


4. How to delete a file in Java ?



public class DeleteFile {
    public static void main(String[] args) {
        try{
            File myFile = new File("javadiscover.txt");
            if(myFile.exists()){
                myFile.delete();
                System.out.println("File deleted successfully....");
            }else{
                System.out.println("File NOT Exisit....");
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
    }
}



OUTPUT:


File deleted successfully....





5. How to rename a file in Java ?

public class RenameFile {
    public static void main(String[] args) {
        File oriFile = new File("java.txt");
        File newFile = new File("javadiscover.txt");
        if(oriFile.exists()){
            oriFile.renameTo(newFile);
            System.out.println("File rename completed....");
        }else{
            System.out.println("Original file not exist for renaming....");
        }
    }
}



OUTPUT:


File rename completed....





Apart from these examples various file operations which you can refer to Oracle docs.







 

Java Date and Time interview questions




In this tutorial we will see about using Java Date and Time-stamp interview questions as,
1. Getting current local Date and Time
2. Converting current local Date and Time to GMT Date and Time
3. Convert String to Date and Time
4. Convert Date and Time to String
5. Adding N days with current Date and Time
6. Subtracting N days with current Date and Time
7. Change Date and Time format
8. Calculate difference between 2 Date
9. Compare 2 Dates

Lets start with simple examples for all above question on Java Date and Time. In all examples we will be using
SimpleDateFormat()
parse()
format()



1. Getting current local Date and Time

public class MyDateTimeTest {
    public static void main(String[] args) {
        Date date = new Date();
        System.out.println("Current Date & Time : "+date);
    }
}

OUTPUT:

Current Date & Time : Sun Mar 17 01:17:30 IST 2013



2. Converting current local Date and Time to GMT Date and Time

public class MyDateTimeTest {
    public static void main(String[] args) {
        Date date = new Date();
        DateFormat gmtFor = new SimpleDateFormat();
        TimeZone gmtTime = TimeZone.getTimeZone("GMT");
          
        gmtFor.setTimeZone(gmtTime);
        System.out.println("Current Date & Time : "+date.toString());
        System.out.println("GMT Time & Date     : " + gmtFor.format(date));
    }
}

OUTPUT:


Current Date & Time : Sun Mar 17 01:29:09 IST 2013
GMT Date & Time     : 3/16/13 7:59 PM



3. Convert String to Date and Time

public class MyDateTimeTest {
    public static void main(String[] args) {
        String myDateTime = "2013-03-17 12:45:56";
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            Date convertedDateTime = df.parse(myDateTime);
            System.out.println("DATE : "+df.format(convertedDateTime));
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
}

OUTPUT:
DATE : 2013-03-17 12:45:56




4. Convert Date and Time to String

public class MyDateTimeTest {
    public static void main(String[] args) {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date convertedDateTime = new Date();
        String dateInString = df.format(convertedDateTime);
        System.out.println("DATE : "+dateInString);
    }
}

OUTPUT:

DATE : 2013-03-17 02:03:09



5. Adding N days with current Date and Time 

public class MyDateTimeTest {
    public static void main(String[] args) {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date currentDateTime = new Date();
        Date newDate = null;
        try {
            newDate = df.parse(df.format(currentDateTime));
            newDate = addNDays(newDate, 10); // Adding 10 days with current Date
            System.out.println("CURRENT DATE              : "+df.format(currentDateTime));
            System.out.println("DATE AFTER ADDING 10 DAYS : "+df.format(newDate));
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
    
    public static Date addNDays(Date date, int days) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.add(Calendar.DATE, days); 
        return cal.getTime();
    }
}

OUTPUT:

CURRENT DATE              : 2013-03-17 02:17:24
DATE AFTER ADDING 10 DAYS : 2013-03-27 02:17:24



6. Subtracting N days with current Date and Time 

public class MyDateTimeTest {
    public static void main(String[] args) {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date currentDateTime = new Date();
        Date newDate = null;
        try {
            newDate = df.parse(df.format(currentDateTime));
            newDate = addNDays(newDate, 10); // Subtracting 10 days with current Date
            System.out.println("CURRENT DATE                   : "+df.format(currentDateTime));
            System.out.println("DATE AFTER SUBTRACTING 10 DAYS : "+df.format(newDate));
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
    
    public static Date addNDays(Date date, int days) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.add(Calendar.DATE, days*-1); 
        return cal.getTime();
    }
}

OUTPUT:

CURRENT DATE                   : 2013-03-17 02:20:12
DATE AFTER SUBTRACTING 10 DAYS : 2013-03-07 02:20:12



7. Change Date and Time format 

public class MyDateTimeTest {
    public static void main(String[] args) {
        DateFormat df1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        DateFormat df2 = new SimpleDateFormat("dd/MMM/yyyy HH:mm:ss aa");
    
        Date currentDateTime = new Date();
        System.out.println("CURRENT DATE      : "+df1.format(currentDateTime));
        System.out.println("NEW FORMATED DATE : "+df2.format(currentDateTime));        
    }
}

OUTPUT:

CURRENT DATE      : 2013-03-17 02:25:59
NEW FORMATED DATE : 17/Mar/2013 02:25:59 AM



8. Calculate difference between 2 Date 

public class MyDateTimeTest {
    public static void main(String[] args) throws ParseException {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String otherDate = "2013-03-15 02:38:45";
        
        Date date1 = new Date();
        Date date2 = df.parse(otherDate);
        
        System.out.println("DATE-1 : "+df.format(date1));
        System.out.println("DATE-2 : "+df.format(date2));    
        long diff = date1.getTime() - date2.getTime();
        
        System.out.println("DATE DIFF : "+(diff/ (1000 * 60 * 60)) +" hours");
    }
}

OUTPUT:

DATE-1 : 2013-03-17 02:38:54
DATE-2 : 2013-03-15 02:38:45
DATE DIFF : 48 hours



9. Compare 2 Dates

public class MyDateTimeTest {
    public static void main(String[] args) throws ParseException {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String otherDate = "2013-03-15 02:38:45";
        
        Date date1 = new Date();
        Date date2 = df.parse(otherDate);
        
        System.out.println("DATE-1 : "+df.format(date1));
        System.out.println("DATE-2 : "+df.format(date2));    
        
        if(date1.compareTo(date2) > 0){
                System.out.println("Date-1 is after Date-2");
            }else if(date1.compareTo(date2) > 0){
                System.out.println("Date-1 is before Date-2");
            }else if(date1.compareTo(date2) == 0){
                System.out.println("Date-1 is equal to Date-2");
            }
        }



OUTPUT:
DATE-1 : 2013-03-17 02:42:37
DATE-2 : 2013-03-15 02:38:45
Date-1 is after Date-2






Java 7 - try-with-resources

In earlier tutorials we have seen couple of Java 7 features like Underscore in numeric literals, Switch Case with non-primitive data-type and Exception handling with multi-catch.

In this tutorial we will see about try-with-resources is a one of the fine feature added in Java 7.
 

For example if we need to allocate a resource for file handling or database connectivity then we need to explicitly close the resource which we have opened in our try block. In those cases it will be tedious to handle lot of resource management manually. In some of the cases we will have try with finally block where we will check for the resource closing. No matter whether the to resource has allocated or not finally block will be executed automatically for all time. Below is the simple example from earlier Java 7 as how we used to handle resources by using file handling.
 



public class MyOldFileHandling {
    public static void main(String[] arg){
        FileInputStream fstream = null;
        DataInputStream istream = null;
        BufferedReader breader = null;
        try {            
            fstream = new FileInputStream("test.txt");
            istream = new DataInputStream(fstream);
            breader = new BufferedReader(new InputStreamReader(istream));
            String line;
            while ((line = breader.readLine()) != null) {
                System.out.println (line);
            }            
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally{
            try{
                /* 
                 * Explicitly all resources need to be closed in 
                 * earlier java versions 
                */

                if(fstream != null)fstream.close();
                if(istream != null)istream.close();
                if(breader != null)breader.close();
            }catch(IOException ioe){
                ioe.printStackTrace();;
            }
        }
    }
}



In above program we can see explicitly programmers need to handle resource closing under finally block, whether resource has or not finally block will be executed compulsory. 

But in Java 7 onwards try-catch-resource feature introduced and programmer need not to worry about resource management once when we add resource in try statement as like bellow.
 



try(FileInputStreamfstream = new FileInputStream("test.txt")) {
.
.
}



Above statement will have same functionality of FileInputStream of our above program. Where as here resource closing close() method will be automatically called once try block completed. Even we can multiple resource under single try block as like below.
 



try(FileInputStreamfstream = new FileInputStream("test.txt");
    DataInputStream istream = new DataInputStream(fstream);
    BufferedReader breader = new BufferedReader(new InputStreamReader(istream))) {
.
.
}

Below example will show same above program will be handled using try-with-resource using Java 7.
 



public class MyNewFileHandling {
        public static void main(String[] arg){
        
        try (FileInputStream fstream = new FileInputStream("test.txt");            
             DataInputStream istream = new DataInputStream(fstream);
             BufferedReader breader = new BufferedReader(new InputStreamReader(istream))) {            
            
            String line;
            while ((line = breader.readLine()) != null) {
                System.out.println (line);
            }            
        } catch (IOException ex) {
            ex.printStackTrace();
        } 
    }
}




 

Drawing image border using Java Code





In our last tutorial we have seen how to re-size image using Java code. In this tutorial we will see how to draw a border in the image using Java code.



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

public class ImageBorder {

    public static void main(String[] args) {
        new ImageBorder().createBorderImage("e:\\tree.jpg", "e:\\tree_border.jpg");
    }
    
    public void createBorderImage(String oriImgUrl, String saveLocFilePath){
        try {
            int borderColor = 0x99FF0000; //Red color
            BufferedImage image = ImageIO.read(new File(oriImgUrl));
            for(int i=0;i < image.setRGB(0, i, borderColor);
                image.setRGB(image.getWidth()-1, i, borderColor);
            }
            for(int i=0;i < image.setRGB(i, 0, borderColor);
                image.setRGB(i, image.getHeight()-1, borderColor);
            }
            ImageIO.write(image, "png"new File(saveLocFilePath));
            
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }
}






Image resizing using Java code




We will see how to re-size image using Java program. Below program will explains you about resizing image using Java code. Method resizeMyImage() will take necessary parameters like re-size image name, original image and resize image sizes (width and height).



import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;

public class ImageResize {
    public static void main(String[] args) {
        // resize_image_name, original_image, resize_image_sizes 
        new ImageResize().resizeMyImage("e:\\rat_resized.jpg", "e:\\rat.jpg", "200", "93");
    }
    
    private void resizeMyImage(String resizeImg, String filePath, String w, String h){
        if(new File(filePath).exists()){
            imageResize(filePath, Integer.parseInt(w) , Integer.parseInt(h), resizeImg);
            System.out.println("Resize completed....");
        }else{
            System.out.println("Original file not exist....");
        }        
    }
    
    public void imageResize(String oriImgUrl, int width, int heigth, String saveLocFilePath){
        try {            
            File f = new File(oriImgUrl);
            BufferedImage image = ImageIO.read(f);
            BufferedImage resizeImage = resize(image, width, heigth);
            ImageIO.write(resizeImage, "jpg"new File(saveLocFilePath));            
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }
    
    private static BufferedImage resize(BufferedImage image, int width, int height) {
        BufferedImage resizedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = resizedImage.createGraphics();
        g.drawImage(image, 0, 0, width, height, null);
        g.dispose();
        return resizedImage;
    }
}






 

Sending SMS through JAVA code

 
In this tutorial we will see about sending SMS through Java code in India. For this first we need to chose some SMS gateway for sending SMS across India and other countries. I have chose www.SMSZone.in for this and will see small example for sending SMS.

Steps to get subscribed:
  • 1. For subscribing we need to provide registered Mobile no. and company / personal details. 
  • 2. Once subscribed need to decide whether we are going to use SMS for promotional or non-promotional activities. 
  • 3. Based on that we need decide our tariff plan and SMS template formats. 
  • 4. Next we need to chose the SenderId for SMS, like JDISCO (only 6 letters are allowed)
  • 5. Next you chose any language for sending SMS like Java, .NET, PHP etc.,


Lets see small Java code for sending SMS by using above SMS gateway.



public class SendSMS {
  
  // SMS Gateway API
  static String SMSApi = "http://www.smszone.in/sendsms.asp?page=SendSmsBulk&username=91XXXX12XXXX&password=XXXX&number=<PHONE>&message=<MSG>&SenderId=JDISCO";
  
  //List of mobile numbers to send SMS
  static String phoneNos = "91XXXX54XXXX, 91XXXX56XXXX";
  
  // SMS text
  static String smsText = "Hi All, Welcome to JavaDiscover";
    
  public static void main(String[] args) {
    try{
      String url = SMSApi.replace("<PHONE>", phoneNos).replace("<MSG>", smsText).replaceAll(" ""%20");
      String smsApiResponse = sendMySMS(url);
      System.out.println(smsApiResponse);
    }catch (Exception e) {
      e.printStackTrace();
    }
  }
  
  public static String sendMySMS(String url){
    StringBuilder output = new StringBuilder();
    try{
      URL hp = new URL(url);
      System.out.println(url);
      URLConnection hpCon = hp.openConnection()
      BufferedReader in = new BufferedReader(new InputStreamReader(hpCon.getInputStream()));
      String inputLine;
      while ((inputLine = in.readLine()) != null)
        output.append(inputLine);
      in.close();
    }catch (Exception e) {
      e.printStackTrace();
    }
    return output.toString();
  }
}




Change you Username, password, phone number and Senderid accordingly.