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

Wednesday, June 4, 2014

File Read and Write examples in Java

Here is the code of java program to Read text File Line by Line:

http://www.roseindia.net/java/beginners/java-read-file-line-by-line.shtml

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("c:\\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());
  }
  }
}


Other way of reading file data:

import java.io.*;
/**
* How To Read File In Java with BufferedReader class
*
*/
public class ReadUsingBufferedReader {
        public static void main(String[] args) 
        {
                System.out.println("Reading File with BufferedReader class");
                //Name of the file
                String fileName="test.text";
                try{
                
                //Create object of FileReader
                FileReader inputFile = new FileReader(fileName);
                
                //Instantiate the BufferedReader Class
                BufferedReader bufferReader = new BufferedReader(inputFile);

                //Variable to hold the one line data
                String line;
                
                // Read file line by line and print on the console
                while ((line = bufferReader.readLine()) != null)   {
                     System.out.println("File Line is: " + line);
                }
                //Close the buffer reader
                bufferReader.close();
                } 
                catch(Exception e){
                    System.out.println("Error in reading file:" + e.getMessage());                  
                }
        }
}
 
Read a specific line: 

import java.io.*;
public class ReadSpecificLine {

        public static void main(String[] args) {
                String line = "";
                int lineNo;
                try {
                        FileReader fr = new FileReader("new.txt");
                        BufferedReader br = new BufferedReader(fr);
                        for (lineNo = 1; lineNo < 10; lineNo++) {
                                if (lineNo == 5) {
                                        line = br.readLine();
                                } else
                                        br.readLine();
                        }
                } catch (IOException e) {
                        e.printStackTrace();
                }
                System.out.println("Line: " + line);
        }
}
 
 

Java read file in memory

import java.io.*;
import java.nio.*;
import java.nio.channels.*;
public class ReadFileInMemory {
        public static void main(String[] args) throws Exception {
             File f = new File("C:/hello.txt");
             long length = f.length();
             MappedByteBuffer buffer = new FileInputStream(f).getChannel().map(
                                FileChannel.MapMode.READ_ONLY, 0, length);
             int i = 0;
             while (i < length) {
                    System.out.print((char) buffer.get(i++));
             }
             System.out.println();
        }
}
 
Reading binary file into byte array in Java 
 
import java.io.*;
public class ReadingBinaryFileIntoByteArray
{
        public static void main(String[] args) 
        {
                System.out.println("Reading binary file into byte array example");
                try{
                        //Instantiate the file object
                        File file = new File("test.zip");
                        //Instantiate the input stread
                        InputStream insputStream = new FileInputStream(file);
                        long length = file.length();
                        byte[] bytes = new byte[(int) length];

                         insputStream.read(bytes);
                         insputStream.close();
        
                         String s = new String(bytes);
                        //Print the byte data into string format
                         System.out.println(s);
                 }
                 catch(Exception e){
                        System.out.println("Error is:" + e.getMessage());
                }
        }
} 

Writing a file using Appending:

import java.io.*;
class WriteToFileWithoutOverwriting {
 public static void main(String args[])
  {
  try{
          FileWriter fstream = new FileWriter("log.txt",true);
          BufferedWriter out = new BufferedWriter(fstream);
          out.write("Line Added on: " + new java.util.Date()+"\n");
          out.close();
    }catch (Exception e){
         System.err.println("Error while writing to file: " +
          e.getMessage());
    }
  }
}
 

Copying Characters from One file to Another file (Copy file):

import java.io.*;

class CopyCharacters {
        public static void main(String[] args) {
           File inFile = new File("input.dat");
           File outFile = new File("output.dat");

           FileReader ins = null;
           FileWriter outs = null;

           try {
                ins = new FileReader(inFile);
                outs = new FileWriter(outFile);

                int ch;
                while((ch = ins.read()) != -1) 
                {
                    outs.write(ch);
                }
            }
            catch(IOException e) {
                   System.out.println(e);
                   System.exit(-1);
            }
            finally {
                   ins.close();
                   outs.close();
            }
       }
  }

Writing Bytes to a file:

import java.io.*;

class WriteBytes {
        public static void main(String[] args) {
           byte cities[] = {'D', 'E', 'L', 'H', 'I', '\n', 'M','A','D','R','S','\n'}
         
           FileOutputStream outfile = null;
 
           try {
                 outfile = new FileOutputStream("city.txt");
                 outfile.write(cities);
                 outfile.close();
           }
           catch(IOException e) {
                  System.out.println(e);
                  System.exit(-1);
           }
     }
 }
 
Reading bytes from file

import java.io.*;

class ReadBytes {
        public static void main(String[] args) {
            FileInputStream infile = null;
            
            int b;
            try {
                  infile = new FileInputStream(args[0]);
                  while ((b = infile.read())!= -1)
                  {
                      System.out.println((char)b);
                  }
                  infile.close(); 
             }
             catch( IOException e)
             {
                  System.out.println(e);
              }
       }
  }
 
 
 

Tuesday, January 28, 2014

File I/O - Examples1

Create a File in Java


import java.io.File;
import java.io.IOException;
 
public class CreateFileExample 
{
    public static void main( String[] args )
    { 
     try {
 
       File file = new File("c:\\newfile.txt");
 
       if (file.createNewFile()){
         System.out.println("File is created!");
       }else{
         System.out.println("File already exists.");
       }
 
     } catch (IOException e) {
       e.printStackTrace();
 }
    }
}
Set File Permission in Java

import java.io.File;
import java.io.IOException;
 
public class FilePermissionExample 
{
    public static void main( String[] args )
    { 
     try {
 
       File file = new File("/mkyong/shellscript.sh");
 
       if(file.exists()){
        System.out.println("Is Execute allow: " +file.canExecute());
    System.out.println("Is Write allow : " + file.canWrite());
    System.out.println("Is Read allow : " + file.canRead());
       }
 
       file.setExecutable(false);
       file.setReadable(false);
       file.setWritable(false);
 
       System.out.println("Is Execute allow : " + file.canExecute());
       System.out.println("Is Write allow : " + file.canWrite());
       System.out.println("Is Read allow : " + file.canRead());
 
       if (file.createNewFile()){
         System.out.println("File is created!");
       }else{
         System.out.println("File already exists.");
       }
 
     } catch (IOException e) {
       e.printStackTrace();
     }
    }
}
Get file path of a file in Java

import java.io.File;
import java.io.IOException;
 
public class AbsoluteFilePathExample
{
    public static void main(String[] args)
    { 
     try{
 
         File temp = File.createTempFile("i-am-a-temp-file", ".tmp" );
 
         String absolutePath = temp.getAbsolutePath();
         System.out.println("File path : " + absolutePath);
 
         String filePath = absolutePath.
               substring(0,absolutePath.lastIndexOf(File.separator));
 
         System.out.println("File path : " + filePath);
 
     }catch(IOException e){
 
         e.printStackTrace();
 
     }
 
    }
}
Get Free disk space in Java

import java.io.File;
 
public class DiskSpaceDetail
{
    public static void main(String[] args)
    { 
     File file = new File("c:");
     long totalSpace = file.getTotalSpace(); //total disk space in bytes.
     long usableSpace = file.getUsableSpace(); // available space in bytes.
     long freeSpace = file.getFreeSpace(); //unallocated space in bytes.
 
     System.out.println(" === Partition Detail ===");
 
     System.out.println(" === bytes ===");
     System.out.println("Total size : " + totalSpace + " bytes");
     System.out.println("Space free : " + usableSpace + " bytes");
     System.out.println("Space free : " + freeSpace + " bytes");
 
     System.out.println(" === mega bytes ===");
     System.out.println("Total size : " + totalSpace /1024 /1024 + " mb");
     System.out.println("Space free : " + usableSpace /1024 /1024 + " mb");
     System.out.println("Space free : " + freeSpace /1024 /1024 + " mb");
    }
}
Check if a file Exists

import java.io.*;
 
public class FileChecker {
 
  public static void main(String args[]) {
 
   File f = new File("c:\\mkyong.txt");
 
   if(f.exists()){
    System.out.println("File existed");
   }else{
    System.out.println("File not found!");
   }
 
  }
 
}
Delete a file in Java

import java.io.File;
 
public class DeleteFileExample
{
    public static void main(String[] args)
    { 
     try{
 
      File file = new File("c:\\logfile20100131.log");
 
      if(file.delete()){
       System.out.println(file.getName() + " is deleted!");
      }else{
       System.out.println("Delete operation is failed.");
      }
 
     }catch(Exception e){
 
      e.printStackTrace();
 
     }
 
    }
}
Get file size in Java


import java.io.File;
 
public class FileSizeExample 
{
    public static void main(String[] args)
    { 
  File file =new File("c:\\java_xml_logo.jpg");
 
  if(file.exists()){
 
   double bytes = file.length();
   double kilobytes = (bytes / 1024);
   double megabytes = (kilobytes / 1024);
   double gigabytes = (megabytes / 1024);
   double terabytes = (gigabytes / 1024);
   double petabytes = (terabytes / 1024);
   double exabytes = (petabytes / 1024);
   double zettabytes = (exabytes / 1024);
   double yottabytes = (zettabytes / 1024);
 
   System.out.println("bytes : " + bytes);
   System.out.println("kilobytes : " + kilobytes);
   System.out.println("megabytes : " + megabytes);
   System.out.println("gigabytes : " + gigabytes);
   System.out.println("terabytes : " + terabytes);
   System.out.println("petabytes : " + petabytes);
   System.out.println("exabytes : " + exabytes);
   System.out.println("zettabytes : " + zettabytes);
   System.out.println("yottabytes : " + yottabytes);
  }else{
    System.out.println("File does not exists!");
  }
 
    }
}
Get the number of lines in a file

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.LineNumberReader;
 
public class LineNumberReaderExample 
{
    public static void main(String[] args)
    { 
 
     try{
 
      File file =new File("c:\\ihave10lines.txt");
 
      if(file.exists()){
 
          FileReader fr = new FileReader(file);
          LineNumberReader lnr = new LineNumberReader(fr);
 
          int linenumber = 0;
 
                 while (lnr.readLine() != null){
              linenumber++;
                 }
 
                 System.out.println("Total # of lines : " + linenumber);
 
                 lnr.close();
 
 
      }else{
        System.out.println("File does not exists!");
      }
 
     }catch(IOException e){
      e.printStackTrace();
     }
 
    }
}
List files with certain extension (filter listing of files)

import java.io.File;
import java.io.FilenameFilter;

public class FileDemo {
   public static void main(String[] args) {
      
      File f = null;
      File[] paths;
      
      try{      
         // create new file
         f = new File("c:/test");
         
         // create new filename filter
         FilenameFilter fileNameFilter = new FilenameFilter() {
   
            @Override
            public boolean accept(File dir, String name) {
               if(name.lastIndexOf('.')>0)
               {
                  // get last index for '.' char
                  int lastIndex = name.lastIndexOf('.');
                  
                  // get extension
                  String str = name.substring(lastIndex);
                  
                  // match path name extension
                  if(str.equals(".txt"))
                  {
                     return true;
                  }
               }
               return false;
            }
         };
         // returns pathnames for files and directory
         paths = f.listFiles(fileNameFilter);
         
         // for each pathname in pathname array
         for(File path:paths)
         {
            // prints file and directory paths
            System.out.println(path);
         }
      }catch(Exception e){
         // if any error occurs
         e.printStackTrace();
      }
   }
}
Rename a file in Java

import java.io.File;
 
public class RenameFileExample 
{
    public static void main(String[] args)
    { 
 
  File oldfile =new File("oldfile.txt");
  File newfile =new File("newfile.txt");
 
  if(oldfile.renameTo(newfile)){
   System.out.println("Rename succesful");
  }else{
   System.out.println("Rename failed");
  }
 
    }
}
Copy a file in Java

Java didn’t comes with any ready make file copy function, you have to manual create the file copy process. To copy file, just convert the file into a bytes stream with FileInputStream and write the bytes into another file with FileOutputStream.

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 afile =new File("Afile.txt");
         File bfile =new File("Bfile.txt");
 
         inStream = new FileInputStream(afile);
         outStream = new FileOutputStream(bfile);
 
         byte[] buffer = new byte[1024];
 
         int length;
         //copy the file content in bytes 
         while ((length = inStream.read(buffer)) > 0){
 
          outStream.write(buffer, 0, length);
 
         }
 
         inStream.close();
         outStream.close();
 
         System.out.println("File is copied successful!");
 
     }catch(IOException e){
      e.printStackTrace();
     }
    }
}
Move file to a different directory

Java.io.File does not contains any ready make move file method, but you can workaround with the following two alternatives :
  1. File.renameTo().
  2. Copy to new file and delete the original file.
Rename
import java.io.File;
 
public class MoveFileExample 
{
    public static void main(String[] args)
    { 
     try{
 
        File afile =new File("C:\\folderA\\Afile.txt");
 
        if(afile.renameTo(new File("C:\\folderB\\" + afile.getName()))){
      System.out.println("File is moved successful!");
        }else{
      System.out.println("File is failed to move!");
        }
 
     }catch(Exception e){
      e.printStackTrace();
     }
    }
}
Copy and Delete

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 MoveFileExample 
{
    public static void main(String[] args)
    { 
 
     InputStream inStream = null;
 OutputStream outStream = null;
 
     try{
 
         File afile =new File("C:\\folderA\\Afile.txt");
         File bfile =new File("C:\\folderB\\Afile.txt");
 
         inStream = new FileInputStream(afile);
         outStream = new FileOutputStream(bfile);
 
         byte[] buffer = new byte[1024];
 
         int length;
         //copy the file content in bytes 
         while ((length = inStream.read(buffer)) > 0){
 
          outStream.write(buffer, 0, length);
 
         }
 
         inStream.close();
         outStream.close();
 
         //delete the original file
         afile.delete();
 
         System.out.println("File is copied successful!");
 
     }catch(IOException e){
         e.printStackTrace();
     }
    }
}
Get file Creation Date in Java

There are no official way to get the file creation date in Java.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
 
public class GetFileCreationDateExample
{
    public static void main(String[] args)
    { 
 
     try{
 
      Process proc = 
         Runtime.getRuntime().exec("cmd /c dir c:\\logfile.log /tc");
 
      BufferedReader br = 
         new BufferedReader(
            new InputStreamReader(proc.getInputStream()));
 
      String data ="";
 
      //it's quite stupid but work
      for(int i=0; i<6; i++){
       data = br.readLine();
      }
 
      System.out.println("Extracted value : " + data);
 
      //split by space
      StringTokenizer st = new StringTokenizer(data);
      String date = st.nextToken();//Get date
      String time = st.nextToken();//Get time
 
      System.out.println("Creation Date  : " + date);
      System.out.println("Creation Time  : " + time);
 
     }catch(IOException e){
 
      e.printStackTrace();
 
     }
 
    }
}
Get the last modified Date in Java

import java.io.File;
import java.text.SimpleDateFormat;
 
public class GetFileLastModifiedExample
{
    public static void main(String[] args)
    { 
 File file = new File("c:\\logfile.log");
 
 System.out.println("Before Format : " + file.lastModified());
 
 SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
 
 System.out.println("After Format : " + sdf.format(file.lastModified()));
    }
}
Change the last Modified Data for a file in Java

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
 
public class ChangeFileLastModifiedExample
{
    public static void main(String[] args)
    { 
 
     try{
 
      File file = new File("C:\\logfile.log");
 
      //print the original last modified date
      SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
      System.out.println("Original Last Modified Date : " 
        + sdf.format(file.lastModified()));
 
      //set this date 
      String newLastModified = "01/31/1998";
 
      //need convert the above date to milliseconds in long value 
      Date newDate = sdf.parse(newLastModified);
      file.setLastModified(newDate.getTime());
 
      //print the latest last modified date
      System.out.println("Lastest Last Modified Date : " 
        + sdf.format(file.lastModified()));
 
     }catch(ParseException e){
 
      e.printStackTrace();
 
     }
 
    }
}
Make a file read only in Java


import java.io.File;
import java.io.IOException;
 
public class FileReadAttribute
{
 
    public static void main(String[] args) throws IOException
    { 
     File file = new File("c:/file.txt");
 
     //mark this file as read only, since jdk 1.2
     file.setReadOnly();
 
     if(file.canWrite()){
          System.out.println("This file is writable");
     }else{
          System.out.println("This file is read only");
     }
 
     //revert the operation, mark this file as writable, since jdk 1.6
     file.setWritable(true);
 
     if(file.canWrite()){
          System.out.println("This file is writable");
     }else{
          System.out.println("This file is read only");
     }    
    }
}
How to generate a file checksum in Java

Here is a simple example to demonstrate how to generate a file checksum value with “SHA-1” mechanism in Java.

import java.io.FileInputStream;
import java.security.MessageDigest;
 
public class TestCheckSum {
 
  public static void main(String args[]) throws Exception {
 
    String datafile = "c:\\INSTLOG.TXT";
 
    MessageDigest md = MessageDigest.getInstance("SHA1");
    FileInputStream fis = new FileInputStream(datafile);
    byte[] dataBytes = new byte[1024];
 
    int nread = 0; 
 
    while ((nread = fis.read(dataBytes)) != -1) {
      md.update(dataBytes, 0, nread);
    };
 
    byte[] mdbytes = md.digest();
 
    //convert the byte to hex format
    StringBuffer sb = new StringBuffer("");
    for (int i = 0; i < mdbytes.length; i++) {
     sb.append(Integer.toString((mdbytes[i] & 0xff) + 0x100, 16).substring(1));
    }
 
    System.out.println("Digest(in hex format):: " + sb.toString());
 
  }
}
Check if a file is hidden in Java

import java.io.File;
import java.io.IOException;
 
public class FileHidden
{
 
    public static void main(String[] args) throws IOException
    { 
     File file = new File("c:/hidden-file.txt");
 
     if(file.isHidden()){
      System.out.println("This file is hidden");
     }else{
      System.out.println("This file is not hidden");
     }
    }
}

Note
The isHidden() method is system dependent, on UNIX platform, a file is considered hidden if it’s name is begins with a “dot” symbol (‘.’); On Microsoft Windows platform, a file is considered to be hidden, if it’s marked as hidden in the file properties.

Creating a temporary file in Java

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

class TempFileDemo
{
   public static void main(String[] args) throws IOException
   {
      System.out.println(System.getProperty("java.io.tmpdir"));
      File temp = File.createTempFile("text", ".txt");
      System.out.println(temp);
      temp.deleteOnExit();
   }
}



List all the files and folders from a directory(not recursive)
  /**
     * List all the files and folders from a directory
     * @param directoryName to be listed
     */
    public void listFilesAndFolders(String directoryName){
        File directory = new File(directoryName);
        //get all the files from a directory
        File[] fList = directory.listFiles();
        for (File file : fList){
            System.out.println(file.getName());
        }
    }

List all the files from a directory
/**
     * List all the files under a directory
     * @param directoryName to be listed
     */
    public void listFiles(String directoryName){
        File directory = new File(directoryName);
        //get all the files from a directory
        File[] fList = directory.listFiles();
        for (File file : fList){
            if (file.isFile()){
                System.out.println(file.getName());
            }
        }
    }

List all the folders from a directory (not including recursive sub folders)
/**
     * List all the folder under a directory
     * @param directoryName to be listed
     */
    public void listFolders(String directoryName){
        File directory = new File(directoryName);
        //get all the files from a directory
        File[] fList = directory.listFiles();
        for (File file : fList){
            if (file.isDirectory()){
                System.out.println(file.getName());
            }
        }
    }

List all files from a directory and sub-directories (recursive)
    /**
     * List all files from a directory and its subdirectories
     * @param directoryName to be listed
     */
    public void listFilesAndFilesSubDirectories(String directoryName){
        File directory = new File(directoryName);
        //get all the files from a directory
        File[] fList = directory.listFiles();
        for (File file : fList){
            if (file.isFile()){
                System.out.println(file.getAbsolutePath());
            } else if (file.isDirectory()){
                listFilesAndFilesSubDirectories(file.getAbsolutePath());
            }
        }
    }