Search Java Programs

Friday, February 5, 2010

Getting the Current Working Directory in Java

Introduction
In this section, you will learn how to get the current working directory. The current working directory that means where your program run. This program shows the current directory name when your program run. Following methods are invoked for this purpose :
System.getProperty("user.dir");

This is the getProperty() method of the System class of the java.lang package returns the system properties according to the indicated argument. Here, the mentioned indicated argument is "user.dir" which indicates about the getting the current directory name.
Here is the code of the program :

import java.io.*;

 
public class  GetCurrentDir{
 
  private static void dirlist(String fname){
 
   File dir = new File(fname);
  
  System.out.println("Current Working Directory : "+ dir);
 
  }

 
 public static void main(String[] args){
 
    String currentdir = System.getProperty("user.dir");
 
    dirlist(currentdir);
 
 }
 
} 
Output of the program 
C:\nisha>javac GetCurrentDir.java

C:\nisha>java GetCurrentDir
Current Working Directory : C:\nisha

C:\nisha>

Traversing files and directories

This section you will learn how the files and subdirectories are traversed lying under a directory. We can find that, how many files and directories are available within a directory. This is very frequently used where lot of work depends on the files and directories. .
The given program describes how you can traverse a directory if it contains directory and files under it. If the directory contains no files and directory then it will tell you that the directory contains no directory and files in it, if it contains a directory and files in it then it will display all the files and directories.
To implement this program, first make a class named as TraversingFileAndDirectories then make an object of File class and pass any directory and filename to its constructor. After that, check it whether the file or directory you have entered is a directory or a file. If it is a directory then it will display that it is a directory otherwise not a directory. If it is a directory, it checks whether it contains more directory and files in it. If it contains then it will display you the list of the files and directories.

Code of the program is given below

import java.io.*;


 
public class TraversingFileAndDirectories{
 
 public static void main(String args[]){
  
  String dirname = args[0];
 
    File file = new File(dirname); 
 
        if(file.isDirectory()){
 
      System.out.println("Directory is  " + dirname);
   
   String str[] = file.list();
 
      for( int i = 0; i<str.length; i++){
  
      File f=new File(dirname + " / " + str[i]);
  
      if(f.isDirectory()){
   
       System.out.println(str[i] + " is a directory");
 
        }
 
       else{
 
         System.out.println(str[i] + " is a file");
 
        }
 
      }
 
    }
  
  else{
 
      System.out.println(dirname  + " is not a directory");
 
    }

  }

} 

Output of the program 
C:\java>java TraversingFileAndDirectories chandan
Directory is chandan
ConstructingFileNamePath.java is a file
constructingfilenamepath.shtml is a file
EnterValuesFromKeyboard.java is a file
entervaluesfromkeyboard.shtml is a file
Factorial.java is a file
factorial.shtml is a file
UseOfThisOperator.java is a file
useofthisoperator.shtml is a file
Download this program

Copy Directory or File in Java

Introduction
Java has the features of the copying the directory and it's contents. This example shows how to copy the directory and files into a new directory.
In this program, you will see how contains of a directory or a file is copied  from the specified source directory (subdirectories and files) to specified destination directory. If you specify the unknown source directory which does not exist then the program gives the output message like : File or directory does not exist. otherwise read the source directory name and create the OutputStream instance for the destination directory while if you specify the unknown destination directory name then the program creates new directory with that name for the destination directory where the contents of the source directory have to be copied.
In this program, there are two methods have been used to complete the program. These methods are explained ahead :
copyDirectory (File srcPath, File dstPath):

The copyDirectory() method is used to copy contents from the specified source directory to the specified destination directory. This method takes two File type arguments passed by the calling method in the main method and check whether the specified directory is a directory exactly or not. If the specified name is in the exact directory format and that exists then the method generates the list of all the sub directories and file inside the source directory using the list() method and copy one by one to the destination directory otherwise the specified name is copies (treated) as a file name directly.
And another method is the main method in which the program read the source and destination directory or file name.
Here is the code of the program : 



import java.io.*;

  public class CopyDirectory{
 
 public static void main(String[] args) throws IOException{
 
   CopyDirectory cd = new CopyDirectory();
    BufferedReader in = new BufferedReader
                        (new InputStreamReader(System.in));
    System.out.println("Enter the source directory or file name : ");

      String source = in.readLine();

    File src = new File(source);
 
    System.out.println("Enter the destination 
                 directory or file name : ");
    String destination = in.readLine();
  
      File dst = new File(destination); 

    cd.copyDirectory(src, dst);

  }
  

  public void copyDirectory(File srcPath, File dstPath)
                               throws IOException{
  
  if (srcPath.isDirectory()){

      if (!dstPath.exists()){

        dstPath.mkdir();
 
     }

 
     String files[] = srcPath.list();
  
    for(int i = 0; i < files.length; i++){
        copyDirectory(new File(srcPath, files[i]), 
                     new File(dstPath, files[i]));
 
      }

    }
 
   else{
 
      if(!srcPath.exists()){

        System.out.println("File or directory does not exist.");
 
       System.exit(0);

      }
      
else
 
      {
 
       InputStream in = new FileInputStream(srcPath);
       OutputStream out = new FileOutputStream(dstPath); 
                     // Transfer bytes from in to out
            byte[] buf = new byte[1024];
 
              int len;
 
           while ((len = in.read(buf)) > 0) {
 
          out.write(buf, 0, len);

        }
 
       in.close();
 
           out.close();

      }
 
   }
   
 System.out.println("Directory copied.");
 
 }

}
Output of the Program:
C:\nisha>java CopyDirectory
Enter the source directory or file name :test
Enter the destination directory or file name :dir1
Directory copied.
Download this example.

Java Create Directory - Java Tutorial

Introduction
In the section, you will learn how a directory or subdirectories are created. This program also explains the process of creating all non-existent ancestor directories automatically. We will use the File class to crate the directory.
 File
The File class an abstract representation of file and directory pathnames. File class is used to interact with the files system.


Here is the code for creating directory and all non-existing ancestor directories:

 

import java.io.*;
class CreateDirectory 
{
   public static void main(String args[])
  {
      try{
    String strDirectoy ="test";
    String strManyDirectories="dir1/dir2/dir3";

    // Create one directory
    boolean success = (new File(strDirectoy)).mkdir();
    if (success) {
      System.out.println("Directory: " + strDirectoy + " created");
    }    
  
    // Create multiple directories
    success = (new File(strManyDirectories)).mkdirs();
    if (success) {
      System.out.println("Directories: " + strManyDirectories + " created");
    }

    }catch (Exception e){//Catch exception if any
      System.err.println("Error: " + e.getMessage());
    }
  }
}
Output of the program: 
C:\nisha>javac CreateDirectory.java

C:\nisha>java CreateDirectory
Directory: test created
Directories: dir1/dir2/dir3 created

C:\nisha>
This program takes inputs to create a directory "test" and subdirectories "dir1\dir2\dir3". the mkdir( ) method is used to create a single directory while the mkdirs( ) method is used to create multiple subdirectories.
Download the code

Getting a absolute path

To find a file or directory it is very necessary to know the path of the file or directory so that you can access it. If you know the path then it is very easy to work on it. Suppose a situation where a problem comes in front you where you don't know the path of the file, then what will you do. Then this problem can be solved by using a method getAbsolutePath().The method getAbsolutePath() should be used where we don't know the exact path of the file.
To find an absolute path of a file, Firstly we have to make a class GetAbsolutePath. Inside this class define the main method. Inside this method  define a File class of java.io package. Inside the constructor of a File class pass the name of the file whose absolute path you want to know. Now call the method getAbsolutePath() of the File class by the reference of  File class and store it in a String variable. Now print the string, you will get a absolute path of the file.
In this class we have make use of the following things by which this problem can be solved.

File: It is class in java.io package. It implements Comparable and Serializable interface.
getAbsolutePath():  It returns the absolute path name in  the form of string.
Code of the program is given below:
import java.io.*;

  public class  GetAbsolutePath{
 
 public static void main(String[] args){
 
   String str = args[0];


      File file = new File(str);
    String absolutePathOfFirstFile = file.getAbsolutePath();

    System.out.println(" The absolute path in first form is " 
                          + absolutePathOfFirstFile);


      file = new File( "chandan" + File.separatorChar+ str);
    String absolutePathOfSecondFile = file.getAbsolutePath();
    System.out.println(" The absolute path is " + absolutePathOfSecondFile);


      file = new File("chandan" + File.separator + ".." + File.separator + str);
    String absolutePathOfThirdFile = file.getAbsolutePath();
    System.out.println(" The absolute path is " + absolutePathOfThirdFile); 

    }
 
} 

Output of the program 
C:\java>java GetAbsolutePath chandan
The absolute path in first form is C:\tapan\chandan
The absolute path is C:\tapan\chandan\chandan
The absolute path is C:\tapan\chandan\..\chandan
Download this example.
Getting the Parents of a Filename
Program uses getParent( ) method of the File class object to find the parent directory name of the current directory. For example,
System.getProperty("user.dir"):
This method returns the user's current directory. The getProperty() method is the system method which is imported from the System class of the java.lang.*; package. This method tells about the system property according to the indicating argument. Here, the indicating argument user.dir indicates about the current directory.
Here is the code of the program : 

import java.io.*;

  public class  GetParentDir{
 
 private static void dirlist(String fname){

    File dir = new File(fname);

    String parentpath = dir.getParent();
  
  System.out.println("Current Directory : "+ dir);

    System.out.println("parent Directory : "+ parentpath);
 
 }

 
  public static void main(String[] args){
 
   String currentdir = System.getProperty("user.dir");

    dirlist(currentdir);
 
 }

} 

Output of the program 
C:\nisha>javac GetParentDir.java

C:\nisha>java GetParentDir
Current Directory : C:\nisha
parent Directory : C:\

C:\nisha>
Download this example.

Delete temp file

In this section, you will learn how a temporary  file is deleted from the current working directory. Java provides deleteOnExit() method for deleting a temporary file. 
Description of program:
This program deletes a temp file from the current working directory which is created for the current session. This program takes a file name that have ".temp" extension and checks it through the exists() method whether it does exist or not. When the file is exist, it will delete the specified file using the deleteOnExit() method and display a message " file is deleted!"; Otherwise  it will show a message "File does not exists!". 
Description of code:
deleteOnExit( ):
This is the method that is used to delete a file which have to be deleted and terminates the virtual machine. The deletion process is completely successfully only the normal termination of the virtual machine that is defined by the Java Language Specification ( JLS ).

Here is the code of program:
import java.io.*;

 
public class DeleteTempFile{
 
 public static void main(String[] args) {
 
   try{
  
    System.out.println("Delete temp file example!");
      BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
      System.out.println("Please enter file name that has '.temp' extension:");
      String str = bf.readLine();
  
    File file = new File(str+".temp");
 
     if (file.exists()){
 
       file.deleteOnExit();
  
      System.out.println("file is deleted!");
 
      }
     
 else{
    
    System.out.println("File does not exists!");
  
    }
   
 }
  
  catch(IOException e){
 
      e.printStackTrace();
   
 }
 
 }
 
} 

Output of program:
C:\vinod\Math_package>javac DeleteTempFile.java

C:\vinod\Math_package>java DeleteTempFile
Delete temp file example!
Please enter file name that has '.temp' extension:
rose
file is deleted!

Create Temp File

In this section, you will learn how a temporary file is created to the default directory. 
A temporary file is a file that is created to store information temporarily so that the memory can be freed for other purposes. It is beneficial and secure to prevent loss of data when a program performs certain functions. For example, an application "Word" automatically determines where and when temporary files are to be created. The temporary files only exist during the current session of an application as the name suggest "temp".  When the application is shut down, all temporary files are first closed and then deleted.
Description of program:

The following code of program will help you in creating a Temporary File to your default directory. Here we have created a temporary file object. Then we have used a method to get the entire path of the temp file which gets created. The method is tempFile.getAbsolutePath();. We have also used a try and catch block here to catch the exception on occurrence. And if the file could not be created then we will get a message that "temp file not created".


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

public class CTFile {
  public static void main(String[] args){
    File tempFile = null;
    
    try {
      tempFile = File.createTempFile("MyFile.txt", ".tmp" );
      System.out.print("Created temporary file with name ");
      System.out.println(tempFile.getAbsolutePath());
      } catch (IOException ex) {

      System.err.println("Cannot create temp file: " + ex.getMessage());
      } finally {
        if (tempFile != null) {
        }
      }
    }
}
Output of the program:
C:\unique>javac CTFile.java

C:\unique>java CTFile
Created temporary file with name C:\DOCUME~1\ADMINI~1\LOCALS~1\Temp\MyFile.txt49
754.tmp

C:\unique>
Download this example.

Change a file timestamp

Timestamp is a utility to change or  modify the time of a file. Java provides the facility for changing a file timestamp according to the  user reliability.  
Description of program:
This program helps you in changing a file timestamp or modification time in Java. After running this program it will take a file name and its modification date in 'dd-mm-yyyy' format. Then it will check the given file is exist or not using the exists() method. When the file exists, this program will change the date of given file and it will display a message "Modification is successfully!" otherwise it will show "File does not exists!".
Description of code:
setLastModified(long time):
This is the method that sets the last modification time of a file or directory and returns Boolean types values either 'true' or 'false'. If it will  return a 'true' only
when the modification is completely successfully otherwise, it will return 'false'. This method takes following long type data:
        time: This is the time that have to be modified or set. 
getTime():
This is the method that returns the number of milliseconds in GMT format like: 23-04-2007.

Here is the code of program:
import java.io.*;
import java.util.*;

import java.text.*;


public class ChangeFileDate{
 
  public static void main(String[] args) {
 
    try{
 
     System.out.println("Change file timestamp example!");
      BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
      System.out.println("Enter file name with extension:");
 
      String str = bf.readLine();
      System.out.println("Enter last modified date in 'dd-mm-yyyy' format:");
      String strDate = bf.readLine();
 
     SimpleDateFormat sdf= new SimpleDateFormat("dd-MM-yyyy");
 
     Date date = sdf.parse(strDate);
  
    File file = new File(str);
 
      if (file.exists()){

        file.setLastModified(date.getTime());
 
       System.out.println("Modification is successfully!");
   
   }

      else{

        System.out.println("File does not exists!");

      }
   
 }

    catch(Exception e){
 
     e.printStackTrace();

    }
  
}

}
Output of program:
C:\vinod\Math_package>javac ChangeFileDate.java

C:\vinod\Math_package>java ChangeFileDate
Change file timestamp example!
Enter file name with extension:
StrStartWith.shtml
Enter last modified date in 'dd-mm-yyyy' format:
23-04-2007
Modification is successfully!

Java - Deleting the file or Directory

Introduction
In this section, you will learn how a specified file or directory is deleted after checking the existence of the. This topic is related to the I/O (input/output) of java.io package.
In this example we are using File class of java.io package. The File class is an abstract representation of file and directory pathnames. 
Explanation
This program takes an input for the file name to be deleted and deletes the specified file if that exists. We will be declaring a function called deletefile() which deletes the specified directory or file.
deletefile(String file)
The function deletefile(String file) takes file name as parameter. The function creates a new File instance for the file name passed as parameter
File f1 = new File(file);
and delete the file using delete function f1.delete(); which return the Boolean value (true/false). It returns true if and only if the file or directory is successfully deleted; false otherwise.
delete()
Deletes the file or directory denoted by this abstract pathname. If this pathname denotes a directory, then the directory must be empty in order to be deleted. Returns:
true if and only if the file or directory is successfully deleted; false otherwise
Code of the Program :

 

import java.io.*;
 
public class DeleteFile{
 
  private static void deletefile(String file){
 
    File f1 = new File(file);
 
   boolean success = f1.delete();

      if (!success){
  
    System.out.println("Deletion failed.");
 
     System.exit(0);
   }
else{
System.out.println("File deleted.");
}
 }
 
  public static void main(String[] args){
 
    switch(args.length){
 
      case 0: System.out.println("File has not mentioned.");
 
          System.exit(0);
 
      case 1: deletefile(args[0]);
 
         System.exit(0);
  
    default : System.out.println("Multiple files are not allow.");
 
            System.exit(0);
   
 }
  
}
 
}
Download File Deletion Example

Moving file or directory from one directory to another

Introduction
In this section, you will learn how  the contents of a file or a complete directory is moved from one directory to another directory. This program illustrates you the method or procedure for moving a file or directory contents from one directory to another. In this section an example is given for the best illustration of the procedure through which you can easily move contents of the mention file or directory as a source directory to the destination directory. If the mentioned source file or directory does not exist then the following program gives you a message "File or directory does not exist." then the control quits from the program. If the mentioned destination directory does not exist then the program asks you for the creation of the directory with the given name and if you enter "y", it will create a new directory and copy all the files and folders contained in the source directory. This program also asks for the replace folder or file if the mentioned destination file or directory already exists.
For running the program properly you must have to mention the complete path for the source or the destination from/to the files or the folders have to be moved. In the following program there are three methods have been used excepting the main method to complete the program for moving file or complete folder from specified source if exists to destination. These methods are explained one-by-one in brief as follows:
copyDirectory(File sourceDir, File destDir):
This the user define method which is used for the copying directory or folders where it found. This method passes two arguments in which one is the source directory name and another is the destination directory name. Both directory name must must be in the File type format.

copyFile(File source, File dest):
This is also a user defined method i.e. used for copying files from the source directory to the destination directory. This method passes two types of arguments in which one is the source file name and another is the destination file name and both file name must has to be mentioned in the File type format.

delete(File resource):
This is the method which has created in the following program for deleting all the files or the folders that have to be moved from the source to destination. This method starts deletion of files and folders after copying these to the destination directory. This method passes the resource file name which has to be deleted after moving.

import java.io.*;

  import javax.swing.*;
 


public class MovingFile{
 
  public static void main(String[] args) throws IOException{
 
    int a = 0;
 
   BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    System.out.print("Enter the file or directory name that has to be moved : ");
 
   String src = in.readLine();
 
    if(src.equals("")){
 
     System.out.println("Invalid directory or file name.");
 
      System.exit(0);
 
   }
 
   File source = new File(src);
 
    if(!source.exists()){
 
     System.out.println("File or directory does not exist.");
 
      System.exit(0);
 
   }
    
System.out.print("Enter the complete path where file or directory 
                       has to be moved: ");
 
    String dest = in.readLine();
 
    if(dest.equals("")){
 
      System.out.println("Invalid directory or file name.");

        System.exit(0);
 
   }
  
  File destination = new File(dest);


      if(!destination.exists()){
 
      System.out.print("Mentioned directory does not exist.
                   \nDo you want to create a new directory(Y/N)? ");
 
      String chk = in.readLine();
 

      if(chk.equals("Y") || chk.equals("y")){
 
       destination.mkdir();
   
     copyDirectory(source, destination);
 
       a = 1;
  
    }
  
    else if(chk.equals("N") || chk.equals("n")){
 
       System.exit(0);
  
    }
     
 else{
  
      System.out.println("Invalid Entry!");
 
       System.exit(0);
  
    }
    
}
    
else{
 
      int num = JOptionPane.showConfirmDialog(null,                            "Given file or folder name already exists. \nDo you want to replace now?");
 
     if(num == 0){
 
        copyDirectory(source, destination);
  
      a = 1;
    
  }
   
 }
  
  if(a == 1){
 
      System.out.println("File or directory moved successfully.");
 
     if(!delete(source)){
 
       throw new IOException("Unable to delete original folder");
 
     }
 
   }
    else if(a == 0){
  
    System.exit(0);
   
 }
 
 }

 
  public static void copyDirectory(File sourceDir, File destDir)
                throws IOException{
 
   if(!destDir.exists()){
 
      destDir.mkdir();
 
   }
  
  File[] children = sourceDir.listFiles();

      for(File sourceChild : children){
 
     String name = sourceChild.getName();
 
      File destChild = new File(destDir, name);

        if(sourceChild.isDirectory()){
 
       copyDirectory(sourceChild, destChild);
 
      }
     
 else{
  
      copyFile(sourceChild, destChild);
 
     }
   
 }
 
 }
 
 
  public static void copyFile(File source, File dest) throws IOException{
 
   if(!dest.exists()){
  
    dest.createNewFile();
 
    }
   
 InputStream in = null;
 
    OutputStream out = null;
 
    try{
 
     in = new FileInputStream(source);

        out = new FileOutputStream(dest);
 
      byte[] buf = new byte[1024];

        int len;
 
      while((len = in.read(buf)) > 0){
 
        out.write(buf, 0, len);

            }
   
     }
  
  finally{
 
     in.close();
 
           out.close();
 
        }
 
  }

 
 public static boolean delete(File resource) throws IOException{ 

      if(resource.isDirectory()){
 
      File[] childFiles = resource.listFiles();
 
      for(File child : childFiles){
  
      delete(child);
   
   }
   
 }
    
return resource.delete();
 
  }
 
}

Here is the code of the program : 
Output: Here "test" is the root folder and "source" directory already exist in this folder. If you want to move "source" into "destination". Please run program this way...


C:\work\chandan>javac MovingFile.java

C:\work\chandan>java MovingFile
Enter the file or directory name that has to be moved : E:\source
Enter the complete path where file or directory has to moved: c:\work\chandan\destination
Mentioned directory does not exist.
Do you want to create a new directory(Y/N)? y
File or directory moved successfully.

C:\work\chandan>
If you want to move file or directory from other directory .Please enter qualified path of  "source" and destination and run this program this way... 


Download this example

Copy multiple files

In this section, you will learn how the data of multiple files is copied to another file. The java.io package provides this facility. For copping the data of multiple file, you need all files in a specified directory where the contents of all files are to be copied to a specified file. 
Description of program:
The following program copies the data of two files (source files) in a specified file (target file). At the time of execution of this program, it takes the number of file with their names that have to be copied. The last file is a target file that contains all data of the given source files. The method copyfile() copies the contents of all given files to a specific file. When all data are copied to specified file, it will display a message "File copied" otherwise Exception is thrown and data will not be be copied.

import java.io.*;

public class CopyMultipleFiles{

  public static void main(String[] args)throws IOException {
    BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
    System.out.println("Enter Number of files that have to be copied:");
    int n = Integer.parseInt(bf.readLine());
    String fileName[] = new String[n];

    for (int i=0; i<n; i++){
      System.out.println("Enter file name:");
      fileName[i] = bf.readLine();
    }

    for (int j=0; j<n-1; j++){
      copyfile(fileName[j],fileName[j+1]);
    }
    System.out.println("File copied.");
  }

  public static void copyfile(String srFile, String dtFile){
    try{
      File f1 = new File(srFile);
      File f2 = new File(dtFile);
      InputStream in = new FileInputStream(f1);
      //For Append the file.
      OutputStream out = new FileOutputStream(f2,true);

      //For Overwrite the file.
//      OutputStream out = new FileOutputStream(f2);

      byte[] buf = new byte[1024];
      int len;
      while ((len = in.read(buf)) > 0){
        out.write(buf, 0, len);
      }
    in.close();
    out.close();
    }
    catch(FileNotFoundException ex){
      System.out.println(ex.getMessage() + " in the specified directory.");
      System.exit(0);
    }
    catch(IOException e){
      System.out.println(e.getMessage());   
    }
}
Here the data of "LAN.log" file and "CopyMultipleFiles.java" file are copied to the copy.txt file.
C:\vinod>javac CopyMultipleFiles.java

C:\vinod>java CopyMultipleFiles
Enter Number of files that have to be coppied:
3
Enter file name:
LAN.log
Enter file name:
CopyMultipleFiles.java
Enter file name:
copy.txt
File copied.

Java - Copying one file to another

Introduction
This example illustrates how to copy contents from one file to another file. This topic is related to the I/O (input/output) of java.io package.
In this example we are using File class of java.io package. The File class is an abstract representation of file and directory pathnames. This class is an abstract, system-independent view of hierarchical pathnames. An abstract pathname has two components:
  1. An optional system-dependent prefix string,
    such as a disk-drive specifier, "/" for the UNIX root directory, or "\\" for a Win32 UNC pathname, and
  2. A sequence of zero or more string names.
Explanation
This program copies one file to another file. We will be declaring a function called copyfile which copies the contents from one specified file to another specified file.
copyfile(String srFile, String dtFile)
The function copyfile(String srFile, String dtFile) takes both file name as parameter. The function creates a new File instance for the file name passed as parameter
File f1 = new File(srFile);
File f2 = new File(dtFile);
 
and creates another InputStream instance for the input object and OutputStream instance for the output object passed as parameter
InputStream in = new FileInputStream(f1);
OutputStream out = new FileOutputStream(f2); 

and then create a byte type buffer for buffering the contents of one file and write to another specified file from the first one specified file.

byte[] buf = new byte[1024];
// For creating a byte type buffeR
out.write(buf, 0, len); // For writing to another specified file from buffer buf
Code of the Program : 





import java.io.*;
 


public class CopyFile{

  private static void copyfile(String srFile, String dtFile){
 
    try{
 
     File f1 = new File(srFile);

      File f2 = new File(dtFile);

      InputStream in = new FileInputStream(f1);
   

//For Append the file.
//

OutputStream out = new FileOutputStream(f2,true);
//For Overwrite the file.
      OutputStream out = new FileOutputStream(f2);


        byte[] buf = new byte[1024];
  
    int len;
 
     while ((len = in.read(buf)) > 0){
  
      out.write(buf, 0, len);
 
     }
 
     in.close();

      out.close();
 
     System.out.println("File copied.");
 
    }
 
   catch(FileNotFoundException ex){
      
   System.out.println(ex.getMessage() + " in 
                            the specified directory.");
  
    System.exit(0);

    }
 
   catch(IOException e){
  
    System.out.println(e.getMessage());  
    
    }

  }

  public static void main(String[] args){
 
   switch(args.length){
 
      case 0: System.out.println("File has not mentioned.");

            System.exit(0);
 
     case 1: System.out.println("Destination file has not mentioned.");

            System.exit(0);

      case 2: copyfile(args[0],args[1]);
 
         System.exit(0);

      default : System.out.println("Multiple files are not allow.");
 
           System.exit(0);

    }

  }

} 
Output of program:
Here the data of "Hello.java" file is copied to the Filterfile.txt file.
C:\nisha>javac CopyFile.java

C:\nisha>java CopyFile a.java Filterfile.txt
File copied.

C:\nisha>
You can even use this program for copying files from one hard drive to another hard drive.
Download File Copy Example

Rename the File or Directory in Java

Introduction
In this section, you will see that how a file or directory is renamed. This program illustrates you the procedure of doing so. Through this program you can easily rename any type of the file or directory. If you mention the directory (path) with the new file or directory name to rename the old file or directory which has to be renamed then the file or directory will be moved from it's own directory to the specified new directory otherwise file or directory will be moved from it's own directory to the default directory where your program has been running. This program also tells you about the availability of the specified file or directory which has to be renamed.
The method renameTo(new_file_instance) can be used to rename the appropriate file or directory. Method renameTo() renames the specified file or directory and returns a boolean value (true or false). Syntax of the renameTo() method used in this program : 
oldfile.renameTo(newfile)
oldfile : oldfile is the created instance of the File class for holding the specified file or directory name which has to be renamed in the file format.
newfile : newfile is also the instance of File class, which is the new name of file or directory
There are no any typical logic has been used in this program. Simply this program first reads the file or directory name which has to be renamed and then check whether the specified file or directory exists or not. If the specified file or directory exists then the program renames that file or directory into the name specified as parameter to the renameTo() method.
Here is the code of the program : 


import java.io.*;

  public class RenameFileOrDir{
 
 public static void main(String[] args) throws IOException{
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    System.out.print("Please enter the file or directory 
                       name which has to be Renamed : ");
    
                        String old_name = in.readLine();
    File oldfile = new File(old_name);
 
   
      if(!oldfile.exists())
{
 
      System.out.println("File or directory does not exist.");
  
    System.exit(0);

    }
   
    System.out.print("please enter the new file or directory name : ");
 
    String new_name = in.readLine();

    File newfile = new File(new_name);
 
    System.out.println("Old File or directory name : "+ oldfile);
    System.out.println("New File or directory name : "+ newfile);
    boolean Rename = oldfile.renameTo(newfile);
  

      if(!Rename)
{

      System.out.println("File or directory does not rename successfully.");

        System.exit(0);
  
  }
   
 else {

      System.out.println("File or directory rename is successfully.");

    }

  }

} 
Download this example.

Count lines of a particular file

In this section, you will learn how to count the availability of  text lines in the particular file. A file is read before counting lines of a particular file,  . File is a collection of stored information that are arranged in string, rows, columns and lines etc. Try it for getting the lines through the following program.
Description of program:
The following program helps you in counting lines of a particular file. At the execution time of this program, it takes a file name with its extension from a particular directory and checks it using the exists() method. If the file exists, it will count lines of a particular file otherwise it will display a message "File does not exists!". 
Description of code:
FileReader(File file):
This is the constructor of FileReader class that is reliable for reading a character files. It constructs a new FileReader and takes a file name that have to be read. 

FileNumberReader():
This is the constructor of FileNumberReader class. It constructs a new line-numbering reader. It  reads characters and puts into buffer. By default the numbering of line begins
from '0'
Here is the code of program:
import java.io.*;

  public class NumberOfLine{

  public static void main(String[] args) {
 
    try{

      System.out.println("Getting line number of a paritcular file example!");
      BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
      System.out.println("Please enter file name with extension:");
      
      String str = bf.readLine();
 
      File file = new File(str);

      if (file.exists()){

        FileReader fr = new FileReader(file);
   
     LineNumberReader ln = new LineNumberReader(fr);
  
      int count = 0;
 
        while (ln.readLine() != null){
 
          count++;
     
   }
 
       System.out.println("Total line no: " + count);
 
        ln.close();
 
      }
 
      else{
 
       System.out.println("File does not exists!");
 
     }
 
    }

    catch(IOException e){

      e.printStackTrace();

    }

  }

} 

Output of program:
C:\vinod\Math_package>javac NumberOfLine.java

C:\vinod\Math_package>java NumberOfLine
Getting line number of a paritcular file example!
Please enter file name with extension:
AddTwoBigNumbers.shtml
Total line no: 58

Getting the Size of a File in Java

Introduction
In this section you will learn how to get the size (in bytes) of a specified file. you will also learn about the methods that can be used to get the file size. If you give the text based file then the program tells you the number of characters otherwise it will give you the file size in bytes.
Program takes the file name through the keyboard and checks whether the file exists. If the file exists then the length( ) method of the instance of the File class gives you size of the file.
Here is the code of the program : 

import java.io.*;

  public class FileSize{
 

 public static void main(String[] args) throws IOException{
 
   System.out.print("Enter file name : ");
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    File f = new File(in.readLine());
  
  if(f.exists()){
   
   long file_size = f.length();
 
      System.out.println("Size of the file : " + file_size);
 
   }
    
else{
   
   System.out.println("File does not exists.");
 
     System.exit(0);
   
 }
 
 }
 
} 

Output of the Program:
C:\nisha>java FileSize
Enter file name : myfile.txt
Size of the file : 19

C:\nisha>

Download this example.

Append To File - Java Tutoria

introduction
In the section, you will learn how the data is appended to an existing file. We will use the class FileWriter and BufferedWriter to append the data to a file.
 FileWriter
The FileWriter is a class used for writing character files. The constructors of this class assume that the default character encoding and the default byte-buffer size are acceptable. This constructor simply overwrite the contents in the file by the specified string but if you put the boolean value as true with the file name (argument of the constructor) then the constructor append the specified data to the file i.e. the pre-exist data in a file is not overwritten and the new data is appended after the pre-exist data.

BufferedWriter
The BufferWriter class is used to write text to a character-output stream, buffering characters so as to provide for the efficient writing of single characters, arrays, and strings.

Here is the code of java program to write text to a file:


import java.io.*;
class FileWrite 
{
   public static void main(String args[])
  {
      try{
    // Create file 
    FileWriter fstream = new FileWriter("out.txt",true);
        BufferedWriter out = new BufferedWriter(fstream);
    out.write("Hello Java");
    //Close the output stream
    out.close();
    }catch (Exception e){//Catch exception if any
      System.err.println("Error: " + e.getMessage());
    }
  }
}

Java Write To File - Java Tutorial

Introduction
In the section, you will learn how to write data to a file. As we have discussed, the FileOutputStream class is used to write data to a file. 
Lets see an example that writes the data to a file converting into the bytes.
This program first check the existence of the specified file. If the file exist, the data is written to the file through the object
of the FileOutputStream class.


import java.io.*;

public class WriteFile{

    public static void main(String[] args) throws IOException{

      File f=new File("textfile1.txt");
      FileOutputStream fop=new FileOutputStream(f);

      if(f.exists()){
      String str="This data is written through the program";
          fop.write(str.getBytes());

          fop.flush();
          fop.close();
          System.out.println("The data has been written");
          }

          else
            System.out.println("This file is not exist");
    }
  }
Output of the Program 
C:\nisha>javac WriteFile.java

C:\nisha>java WriteFile
The data has been written
C:\nisha>
Download this Program
The another way for writing data to a file, the class FileWriter and BufferedWriter are used.
 FileWriter :
 FileWriter is a subclass of OutputStreamWriter class that is used to write text (as opposed to binary data) to a file. You create a FileWriter by specifying the file to be written to, or optionally, when the data should be appended to the end of an existing file instead of overwriting that file. The FileWriter class creates an internal FileOutputStream to write bytes to the specified file
BufferedWriter :
The BufferedWriter class is used to write text to a character-output stream, buffering characters so as to provide for the efficient writing of single characters, arrays and strings.
The constructor of the
FileWriter class takes the file name which has to be buffered by the BufferedWriter stream. The write( ) method of BufferedWriter class is used to create the file into specified directory.
Following code  write data into new file: 
out.write(read_the_Buffered_file_name);
Following code creates the object of FileWriter and BufferedWriter
FileWriter fstream = new FileWriter(file_name);
BufferedWriter out = new BufferedWriter(fstream);

Lets see an another example that writes the text input by the user using the FileWriter and the BufferedWriter class.


import java.io.*;

public class FileWriter{

  public static void main(String[] args) throws IOException{
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    System.out.print("Please enter the file name to create : ");
    String file_name = in.readLine();
    File file = new File(file_name);
    boolean exist = file.createNewFile();
    if (!exist)
    {
      System.out.println("File already exists.");
      System.exit(0);
    }
    else
    {
      FileWriter fstream = new FileWriter(file_name);
      BufferedWriter out = new BufferedWriter(fstream);
      out.write(in.readLine());
      out.close();
      System.out.println("File created successfully.");
    }
  }
}

Output of the Program 

C:\nisha>javac CreateFile.java

C:\nisha>java CreateFile
Please enter the file name to create : nishu.txt
this is my name
File created successfully.

C:\nisha>
 Download the code

Java read file line by line - Java Tutorial

Introduction
Lets understand some I/O streams that are used to perform reading and writing operation in a file. In the section of Java Tutorial you will learn how to write java program to read file line by line. 
Java supports the following I/O file streams.
  • FileInputstream
  • FileOutputStream 
FileInputstream:
This class is a subclass of Inputstream class that reads bytes from a specified file name . The read() method of this class reads a byte or array of bytes from the file. It returns -1 when the end-of-file has been reached. We typically use this class in conjunction with a BufferedInputStream and DataInputstream class to read binary data. To read text data, this class is used with an InputStreamReader and BufferedReader class. This class throws FileNotFoundException, if the specified file is not exist. You can use the constructor of this stream as:
FileInputstream(File filename);
FileOutputStream:
This class is a subclass of OutputStream that writes data to a specified file name. The write() method of this class writes a byte or array of bytes to the file. We typically use this class in conjunction with a BufferedOutputStream and a DataOutputStream class to write binary data. To write text, we typically use it with a PrintWriter, BufferedWriter and an OutputStreamWriter class. You can use the constructor of this stream as:
FileOutputstream(File filename);
 DataInputStream:
This class is a type of FilterInputStream that allows you to read binary data of Java primitive data types in a portable way. In other words, the DataInputStream class is used to read binary Java primitive data types in a machine-independent way. An application uses a DataOutputStream to write data that can later be read by a DataInputStream. You can use the constructor of this stream as:
DataInputStream(FileOutputstream finp);
The following program demonstrate, how the contains are read from a file.
import java.io.*;

public class ReadFile{
    public static void main(String[] args) throws IOException{
      File f;
    f=new File("myfile.txt");

      if(!f.exists()&& f.length()<0)
      System.out.println("The specified file is not exist");

      else{
         FileInputStream finp=new FileInputStream(f);
      byte b;
    do{
      b=(byte)finp.read();
      System.out.print((char)b);
    }
      while(b!=-1);
        finp.close();
        }
    }
  }

Output of the Program:
C:\nisha>javac ReadFile.java

C:\nisha>java ReadFile
This is a text file?
C:\nisha>
This program reads the bytes from file and display it to the user.
Download this Program
The another program  use DataInputStreams for reading textual input line by line with an appropriate BufferedReader.
import java.io.*;
class FileRead 
{
   public static void main(String args[])
  {
      try{
    // Open the file that is the first 
    // command line parameter
    FileInputStream fstream = new FileInputStream("textfile.txt");
    // Get the object of DataInputStream
    DataInputStream in = new DataInputStream(fstream);
        BufferedReader br = new BufferedReader(new InputStreamReader(in));
    String strLine;
    //Read File Line By Line
    while ((strLine = br.readLine()) != null)   {
      // Print the content on the console
      System.out.println (strLine);
    }
    //Close the input stream
    in.close();
    }catch (Exception e){//Catch exception if any
      System.err.println("Error: " + e.getMessage());
    }
  }
}

Output of the Program:
C:\nisha>javac FileRead.java  C:\nisha>java FileRead
this is a file

C:\nisha>
Download the code

Java read file line by line - Java Tutorial

Introduction
Lets understand some I/O streams that are used to perform reading and writing operation in a file. In the section of Java Tutorial you will learn how to write java program to read file line by line. 
Java supports the following I/O file streams.
  • FileInputstream
  • FileOutputStream 
FileInputstream:
This class is a subclass of Inputstream class that reads bytes from a specified file name . The read() method of this class reads a byte or array of bytes from the file. It returns -1 when the end-of-file has been reached. We typically use this class in conjunction with a BufferedInputStream and DataInputstream class to read binary data. To read text data, this class is used with an InputStreamReader and BufferedReader class. This class throws FileNotFoundException, if the specified file is not exist. You can use the constructor of this stream as:
FileInputstream(File filename);
FileOutputStream:
This class is a subclass of OutputStream that writes data to a specified file name. The write() method of this class writes a byte or array of bytes to the file. We typically use this class in conjunction with a BufferedOutputStream and a DataOutputStream class to write binary data. To write text, we typically use it with a PrintWriter, BufferedWriter and an OutputStreamWriter class. You can use the constructor of this stream as:
FileOutputstream(File filename);
 DataInputStream:
This class is a type of FilterInputStream that allows you to read binary data of Java primitive data types in a portable way. In other words, the DataInputStream class is used to read binary Java primitive data types in a machine-independent way. An application uses a DataOutputStream to write data that can later be read by a DataInputStream. You can use the constructor of this stream as:
DataInputStream(FileOutputstream finp);
The following program demonstrate, how the contains are read from a file.
import java.io.*;

public class ReadFile{
    public static void main(String[] args) throws IOException{
      File f;
    f=new File("myfile.txt");

      if(!f.exists()&& f.length()<0)
      System.out.println("The specified file is not exist");

      else{
         FileInputStream finp=new FileInputStream(f);
      byte b;
    do{
      b=(byte)finp.read();
      System.out.print((char)b);
    }
      while(b!=-1);
        finp.close();
        }
    }
  }

Output of the Program:
C:\nisha>javac ReadFile.java

C:\nisha>java ReadFile
This is a text file?
C:\nisha>
This program reads the bytes from file and display it to the user.
Download this Program
The another program  use DataInputStreams for reading textual input line by line with an appropriate BufferedReader.

import java.io.*;
class FileRead 
{
   public static void main(String args[])
  {
      try{
    // Open the file that is the first 
    // command line parameter
    FileInputStream fstream = new FileInputStream("textfile.txt");
    // Get the object of DataInputStream
    DataInputStream in = new DataInputStream(fstream);
        BufferedReader br = new BufferedReader(new InputStreamReader(in));
    String strLine;
    //Read File Line By Line
    while ((strLine = br.readLine()) != null)   {
      // Print the content on the console
      System.out.println (strLine);
    }
    //Close the input stream
    in.close();
    }catch (Exception e){//Catch exception if any
      System.err.println("Error: " + e.getMessage());
    }
  }
}

Output of the Program:
C:\nisha>javac FileRead.java  C:\nisha>java FileRead
this is a file

C:\nisha>
Download the code

Constructing a File Name path

In Java, it is possible to set dynamic path, which is helpful for mapping local  file name with the actual path of the file using the constructing filename path technique.
As you have seen, how a file is created to the current directory where the program is run. Now we will see how the same program constructs a File object from a more complicated file name, using the static constant File.separator or File.separatorCharto specify the file name in a platform-independent way. If we are using Windows platform then the value of this separator is  ' \ ' .
Lets see an example to create a file to the specified location.

import java.io.*;

public class PathFile{
    public static void main(String[] args) throws IOException{
      File f;
    f=new File("example" + File.separator + "myfile.txt");
      f.createNewFile();
      System.out.println("New file \"myfile.txt\" 

has been created 
                             to the specified location");
      System.out.println("The absolute path of the file is: "
                +f.getAbsolutePath());      
    }
} 
Output of the program:
C:\nisha>javac PathFile.java

C:\nisha>java PathFile
New file "myfile.txt" has been created to the specified location
The absolute path of the file is: C:\nisha\example\myfile.txt
C:\nisha>
Download this Program
Another program set the dynamic path using File.separator given below:


import java.io.*;

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

      String filepath = File.separatorChar + "tapan"
              + File.separatorChar + "joshi";

      System.out.println("The path of the file is  :  " 
              + filepath);
 
       }
 
}

Output of the program:
C:\java>java ConstructingFileNamePath
The path of the file is : \tapan\joshi
Download this example.

Create a File

Introduction
Whenever the data is need to be stored, a file is used to store the data. File is a collection of stored information that are arranged in string, rows, columns and lines etc.
In this section, we will see how to create a file. This example takes the file name and text data for storing to the file.

For creating a new file File.createNewFile( ) method is used. This method returns a boolean value true if the file is created otherwise return false. If the mentioned file for the specified directory is already exist then the createNewFile() method returns the false otherwise the method creates the mentioned file and return true. 
Lets see an example that checks the existence of  a specified file.

import java.io.*;

public class CreateFile1{
    public static void main(String[] args) throws IOException{
      File f;
      f=new File("myfile.txt");
      if(!f.exists()){
      f.createNewFile();
      System.out.println("New file \"myfile.txt\" has been created 
                          to the current directory");
      }
    }
}

First, this program checks, the specified file "myfile.txt" is exist or not. if it does not exist then a new file is created with same name to the current location. 
Output of the Program
C:\nisha>javac CreateFile1.java

C:\nisha>java CreateFile1
New file "myfile.txt" has been created to the current directory

C:\nisha>
If you try to run this program again then after checking the existence of the file, it will not be created and you will see a message as shown in the output.
C:\nisha>javac CreateFile1.java

C:\nisha>java CreateFile1
The specified file is already exist

C:\nisha>
Download this Program

Copy a file to other destination and show the modification time of destination file

This is detailed java code that copies a source file to destination file, this code checks all the condition before copy to destination file, for example- source file is exist or not, source file is readable or not etc.
In the example code given below we have used command line argument as file name, first argument will be path of the source file and second will be the path of destination file. If we provide only file names instead of full path, code will try to search source file in the same directory where java code file has been saved. If destination file is not found in given directory this will create a new file and write content of source file in same, if destination file is already exist code will ask weather you want to overwrite file or not.


CopyFile.java
import java.io.*;
import java.util.*;

public class CopyFile {

    public static void copy(String source, String 
    destination) throws IOException {
        File source_file = new File(source);
        File desti_file = new File(destination);
        FileInputStream fis = null;
        FileOutputStream fos = null;
        byte[] buffer;
        int byte_read;

        try {

            /* first check that file exists or not. */
            if (!source_file.exists() || !source_file.isFile()) 
            {
                throw new ClassException("No source file 
                found : "+source);
            }

        /* check that the file is readable or not. */
            if (!source_file.canRead()) {
                throw new ClassException("Source file is 
                unreadable: "+source);
            }

            /* If the destination exists, make sure it is a 
            writeable file and ask before overwriting it. 
            If the destination doesn't exist, make sure the 
            directory exists and is writeable.*/
            if (desti_file.exists()) {
                if (desti_file.isFile()) {
                    DataInputStream in = 
                    new DataInputStream(System.in);

                    if (!desti_file.canWrite()) {
                        throw new ClassException("Destination 
                        is unwriteable : "+destination);
                    }
                    System.out.print("File " + destination + 
                    " already exists. Overwrite?(Y/N): ");
                    System.out.flush();
                    String response = in.readLine();
                    if (!response.equals("Y") && 
                         !response.equals("y")) {
                        throw new ClassException("Wrong 
                        Input.");
                    }
                } 
        else {
                   throw new ClassException("Destination is 
                   not a normal file: " + destination);
                }
            } 
        else {
                File parentdir = parent(desti_file);
                if (!parentdir.exists()) {
                    throw new ClassException("No Destination 
                    directory exist: " + destination);
                }
                if (!parentdir.canWrite()) {
                    throw new ClassException("Destination 
                    directory is unwriteable: " 
                            + destination);
                }
            }

            /* Now we have checked all the things so we can 
            copy the file now.*/
            fis = new FileInputStream(source_file);
            fos = new FileOutputStream(desti_file);
            buffer = new byte[1024];
            while (true) {
                byte_read = fis.read(buffer);
                if (byte_read == -1) {
                    break;
                }
                fos.write(buffer, 0, byte_read);
            }
        } 

        /* Finally close the stream. */ 
    finally {
              fis.close();
          fos.close();              
        }

        // Access last modification date of destination file.
        System.out.print("Last modification date of 
        destination file : ");
        System.out.println(new Date(desti_file.lastModified()));
    }

    /* File.getParent() can return null when the file is 
    specified without a directory or
    is in the root directory. This method handles those cases.*/
    private static File parent(File f) {
        String dirname = f.getParent();
        if (dirname == null) {
            if (f.isAbsolute()) {
                return new File(File.separator);
            } 
        else {
                return new File(System.getProperty("user.dir"));
            }
        }
        return new File(dirname);
    }

    public static void main(String[] args) {
        if (args.length != 2) {
            System.err.println("Wrong argument entered. 
            Try Again......");
        } 
    else {
            try {
                copy(args[0], args[1]);
            } 
        catch (IOException ex) {
                System.err.println(ex.getMessage());
            }
        }
    }
}

class ClassException extends IOException {

    public ClassException(String msg) {
        super(msg);
    }
}
Output of the program :

Download Source Code

Website Design by Mayuri Multimedia