Showing posts with label I/O-File. Show all posts
Showing posts with label I/O-File. Show all posts

Wednesday, May 9, 2012

How to copy file in java with example

Here is the example of copying file in java. This example will copy file and its content from one file to another.
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
 
public class CopyFileExample 
{
    public static void main(String[] args)
    { 
     InputStream inStream = null;
     OutputStream outStream = null;
     try
     {
         File fileOne =new File("D:\\db\\fileTest\\file2.txt");
         File fileTwo =new File("D:\\db\\fileTest\\file3.txt");
 
         inStream = new FileInputStream(fileOne);
         outStream = new FileOutputStream(fileTwo);
 
         byte[] buffer = new byte[1024];
          int length;
          
         //start copy file content in bytes 
         while ((length = inStream.read(buffer)) > 0)
         {
          outStream.write(buffer, 0, length);
         }
         inStream.close();
         outStream.close();
 
         System.out.println("File copied successfully");
     }
     catch(IOException e)
     {
      e.printStackTrace();
     }
    }
}

How to rename file in java with example

How to rename file in java with example
import java.io.File;

public class FileRenameExample 
{
    public static void main(String[] args)
    { 
 
  File oldFileName =new File("D:\\db\\fileTest\\file1.txt");
  File newFileName =new File("D:\\db\\fileTest\\file2.txt");
 
  if(oldFileName.renameTo(newFileName))
  {
   System.out.println("File Renamed successfully");
  }
  else
  {
   System.out.println("Can not rename file");
  }
    }
}

How to Delete file in Java with example

How to delete file in java code?
Here is the example of delete file operation

import java.io.File;

public class FileDeleteExample
{
    public static void main(String[] args)
    { 
     try
     {
      File file = new File("D:\\db\\fileTest\\file1.txt");
 
      if(file.delete())
      {
       System.out.println(file.getName() + " is deleted successfully");
      }
      else
      {
       System.out.println("Can not delete file");
      }
     }
     catch(Exception e)
     {
      e.printStackTrace();
     }
    }
}

How to add content, append content in File in Java with example using RandomAccessFile

How to Add content ot append content in existing file using RandomAccessFile in Java with Example
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.Date;
 
public class ContentAppendToFileExample 
{
    public static void main( String[] args )
    { 
     try 
     {
     String contentToAddedAtTheEndOfFile = "\nThis content will added/append to the end of the file at "+new Date();
     File file =new File("D:\\db\\fileTest\\file1.txt");
         RandomAccessFile raf = new RandomAccessFile(file, "rw");

         // Seek to end of file
         raf.seek(file.length());

         // Append to the end
         raf.writeBytes(contentToAddedAtTheEndOfFile);
         raf.close();
     } 
     catch (IOException e) 
     {
      e.printStackTrace();
     }
    }
}

How to write content into file in Java using BufferedWriter with example

How to write content into file in Java using BufferedWriter with example 

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

public class WriteFileExampleUsingBufferedWriter
{
  public static void main( String[] args )
    { 
      try
      {
       String fileContent = "Content Added  on "+new Date();
          File file = new File("d:\\db\\fileTest\\newfile.txt");
  
        //first check if the file is already there, if no file found then create new file
    if (!file.exists()) 
    {
     file.createNewFile();
     System.out.println("File Created Succefssfully");
    }
  
          FileWriter fw = new FileWriter(file.getName());
          BufferedWriter bw = new BufferedWriter(fw);
          bw.write(fileContent);
          bw.close();
  
          System.out.println("Content written Succefssfully");
      }
      catch(IOException e)
      {
       e.printStackTrace();
      }
     }
}

How to write content into file in Java using FileOutputStream with example

Here is the example to write content into file using FileOutputStream in Java

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
 
public class WriteFileExampleUsingFileOutputStream
{
 public static void main(String[] args)
 {
  FileOutputStream fos = null;
  File file;
  String fileContent = "Content Added  on "+new Date();
  try 
  {
   file = new File("d:\\db\\fileTest\\newfile.txt");
   fos = new FileOutputStream(file);
 
   //first check if the file is already there, if no file found then create new file
   if (!file.exists()) 
   {
    file.createNewFile();
    System.out.println("File Created Succefssfully");
   }
    // get the content in bytes
   byte[] contentInBytes = fileContent.getBytes();
 
   fos.write(contentInBytes);
   fos.flush();
   fos.close();
 
   System.out.println("Content written Succefssfully");
  } 
  catch (IOException e) 
  {
   e.printStackTrace();
  } 
  finally 
  {
   try
   {
    if (fos != null)
    {
     fos.close();
    }
   } 
   catch (IOException e) 
   {
    e.printStackTrace();
   }
  }
 }
}

How to read file in Java using BufferedReadetr with example

Example to demonstrate how to read a file in Java using BufferedReader classes with example. THis is most simple way to read file in java.
In this example readLine() method is used to read each line from file.

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class ReadFileExample1 
{
 public static void main(String[] args)
 {
  BufferedReader br = null;
  try 
  {
   String thisLise;
   br = new BufferedReader(new FileReader("D:\\db\\fileTest\\file1.txt"));
   while ((thisLise = br.readLine()) != null) 
   {
    System.out.println(thisLise);
   }
  } 
  catch (IOException e)
  {
   e.printStackTrace();
  }
  finally //finally closing the objects
  {
   try
   {
    if (br != null)br.close();
   } 
   catch (IOException ex)
   {
    ex.printStackTrace();
   }
  }
 }
}

How to read file in Java using BufferedInputStream with example

Example to demonstrate how to read a file in Java using BufferedInputStream and DataInputStream classes with example.
In this example readLine() method is used to read each line from file.


import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

public class ReadFileExample
{
    public static void main(String[] args)
    {
        File file = new File("D:\\db\\fileTest\\file1.txt");
        FileInputStream fis = null;
        BufferedInputStream bis = null;
        DataInputStream dis = null;

        try 
        {
            fis = new FileInputStream(file);
            bis = new BufferedInputStream(fis);
            dis = new DataInputStream(bis);

            while (dis.available() != 0)
            {
                String lineString=dis.readLine();
                System.out.println(lineString);
            }
         } 
        catch (IOException e)
        {
            e.printStackTrace();
        }
        finally //finally closing file
        {
            try 
            {
                fis.close();
                bis.close();
                dis.close();
            }
            catch (IOException ex)
            {
                ex.printStackTrace();
            }
        }
    }
}

Create New File Example in Java

Java has provided java.io.file pacakge  to work with File.

To create 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.
here is the example of creating New file in java 

import java.io.File;
import java.io.IOException;

public class CreateNewFileExample 
{
 public static void main(String[] args) 
 {
  new CreateNewFileExample().createFile();
 }
 public void createFile()
 {
  try {
    
        File file = new File("d:\\db\\fileTest\\newfile.txt");
  
        if (file.createNewFile())
        {
         System.out.println("File is created successfully!");
        }
        else
        {
         System.out.println("Cannot create file, file already exists.");
        }
      } 
  catch (IOException e)
  {
        e.printStackTrace();
  }
 }
}