File IO Project


Click here to download eclipse supported ZIP file




The java.io package contains nearly every class you might ever need to perform input and output (I/O) in Java. All these streams represent an input source and an output destination. The stream in the java.io package supports many data such as primitives, Object, localized characters, etc.

Stream

A stream can be defined as a sequence of data. there are two kinds of Streams

  • InPutStream: The InputStream is used to read data from a source.

  • OutPutStream: the OutputStream is used for writing data to a destination.

 

Java I/O Streams

 

Java provides strong but flexible support for I/O related to Files and networks but this tutorial covers very basic functionality related to streams and I/O. We would see most commonly used example one by one:

Byte Streams

Java byte streams are used to perform input and output of 8-bit bytes. Though there are many classes related to byte streams but the most frequently used classes are , FileInputStream and FileOutputStream. Following is an example which makes use of these two classes to copy an input file into an output file:

 

    

package com.cv.java.file.io;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class CopyFile {
   public static void main(String args[]) throws IOException
   {
      FileInputStream in = null;
      FileOutputStream out = null;

      try {
         in = new FileInputStream("input.txt");
         out = new FileOutputStream("output.txt");
         
         int c;
         while ((c = in.read()) != -1) {
            out.write(c);
         }
      }finally {
         if (in != null) {
            in.close();
         }
         if (out != null) {
            out.close();
         }
      }
   }
}

Now let's have a file input.txt with the following content:

This is test for copy file.

As a next step, compile above program and execute it, which will result in creating output.txt file with the same content as we have in input.txt. So let's put above code in CopyFile.java file and do the following:

$javac CopyFile.java
$java CopyFile

Character Streams

Java Byte streams are used to perform input and output of 8-bit bytes, where as Java Character streams are used to perform input and output for 16-bit unicode. Though there are many classes related to character streams but the most frequently used classes are , FileReader and FileWriter.. Though internally FileReader uses FileInputStream and FileWriter uses FileOutputStream but here major difference is that FileReader reads two bytes at a time and FileWriter writes two bytes at a time.

We can re-write above example which makes use of these two classes to copy an input file (having unicode characters) into an output file:

 

    

package com.cv.java.file.io;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class CopyFile {
   public static void main(String args[]) throws IOException
   {
      FileInputStream in = null;
      FileOutputStream out = null;

      try {
         in = new FileInputStream("input.txt");
         out = new FileOutputStream("output.txt");
         
         int c;
         while ((c = in.read()) != -1) {
            out.write(c);
         }
      }finally {
         if (in != null) {
            in.close();
         }
         if (out != null) {
            out.close();
         }
      }
   }
}

Now let's have a file input.txt with the following content:

This is test for copy file.

As a next step, compile above program and execute it, which will result in creating output.txt file with the same content as we have in input.txt. So let's put above code in CopyFile.java file and do the following:

$javac CopyFile.java
$java CopyFile

Standard Streams

All the programming languages provide support for standard I/O where user's program can take input from a keyboard and then produce output on the computer screen. If you are aware if C or C++ programming languages, then you must be aware of three standard devices STDIN, STDOUT and STDERR. Similar way Java provides following three standard streams

  • Standard Input: This is used to feed the data to user's program and usually a keyboard is used as standard input stream and represented as System.in.

  • Standard Output: This is used to output the data produced by the user's program and usually a computer screen is used to standard output stream and represented as System.out.

  • Standard Error: This is used to output the error data produced by the user's program and usually a computer screen is used to standard error stream and represented as System.err.

Following is a simple program which creates InputStreamReader to read standard input stream until the user types a "q":

 

    

package com.cv.java.file.io;

import java.io.IOException;
import java.io.InputStreamReader;

public class ReadConsole {
   public static void main(String args[]) throws IOException
   {
      InputStreamReader cin = null;

      try {
         cin = new InputStreamReader(System.in);
         System.out.println("Enter characters, 'q' to quit.");
         char c;
         do {
            c = (charcin.read();
            System.out.print(c);
         while(c != 'q');
      }finally {
         if (cin != null) {
            cin.close();
         }
      }
   }
}

Let's keep above code in ReadConsole.java file and try to compile and execute it as below. This program continues reading and outputting same character until we press 'q':

$javac ReadConsole.java
$java ReadConsole
Enter characters, 'q' to quit.
1
1
e
e
q
q

Reading and Writing Files:

As described earlier, A stream can be defined as a sequence of data. The InputStream is used to read data from a source and the OutputStream is used for writing data to a destination.

Here is a hierarchy of classes to deal with Input and Output streams.

Java I/O Streams

The two important streams are FileInputStream and FileOutputStream, which would be discussed in this tutorial:

FileInputStream:

This stream is used for reading data from the files. Objects can be created using the keyword new and there are several types of constructors available.

Following constructor takes a file name as a string to create an input stream object to read the file.:

InputStream f = new FileInputStream("C:/java/hello");

Following constructor takes a file object to create an input stream object to read the file. First we create a file object using File() method as follows:

File f = new File("C:/java/hello");
InputStream f = new FileInputStream(f);

Once you have InputStream object in hand, then there is a list of helper methods which can be used to read to stream or to do other operations on the stream.

SN Methods with Description
1 public void close() throws IOException{}

This method closes the file output stream. Releases any system resources associated with the file. Throws an IOException.

2 protected void finalize()throws IOException {}

This method cleans up the connection to the file. Ensures that the close method of this file output stream is called when there are no more references to this stream. Throws an IOException.

3 public int read(int r)throws IOException{}

This method reads the specified byte of data from the InputStream. Returns an int. Returns the next byte of data and -1 will be returned if it's end of file.

4 public int read(byte[] r) throws IOException{}

This method reads r.length bytes from the input stream into an array. Returns the total number of bytes read. If end of file -1 will be returned.

5 public int available() throws IOException{}

Gives the number of bytes that can be read from this file input stream. Returns an int.

There are other important input streams available, for more detail you can refer to the following links:

FileOutputStream:

FileOutputStream is used to create a file and write data into it. The stream would create a file, if it doesn't already exist, before opening it for output.

Here are two constructors which can be used to create a FileOutputStream object.

Following constructor takes a file name as a string to create an input stream object to write the file:

OutputStream f = new FileOutputStream("C:/java/hello") 

Following constructor takes a file object to create an output stream object to write the file. First, we create a file object using File() method as follows:

File f = new File("C:/java/hello");
OutputStream f = new FileOutputStream(f);

Once you have OutputStream object in hand, then there is a list of helper methods, which can be used to write to stream or to do other operations on the stream.

SN Methods with Description
1 public void close() throws IOException{}

This method closes the file output stream. Releases any system resources associated with the file. Throws an IOException

2 protected void finalize()throws IOException {}

This method cleans up the connection to the file. Ensures that the close method of this file output stream is called when there are no more references to this stream. Throws an IOException.

3 public void write(int w)throws IOException{}

This methods writes the specified byte to the output stream.

4 public void write(byte[] w)

Writes w.length bytes from the mentioned byte array to the OutputStream.

There are other important output streams available, for more detail you can refer to the following links:

Example:

Following is the example to demonstrate InputStream and OutputStream:

 

    
package com.cv.java.file.io;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class fileStreamTest{

   public static void main(String args[]){
   
   try{
      byte bWrite [] {11,21,3,40,5};
      OutputStream os = new FileOutputStream("test.txt");
      for(int x=0; x < bWrite.length ; x++){
         os.writebWrite[x] )// writes the bytes
      }
      os.close();
     
      InputStream is = new FileInputStream("test.txt");
      int size = is.available();

      for(int i=0; i< size; i++){
         System.out.print((char)is.read() "  ");
      }
      is.close();
   }catch(IOException e){
      System.out.print("Exception");
   }  
   }
}

The above code would create file test.txt and would write given numbers in binary format. Same would be output on the stdout screen.

File Navigation and I/O:

There are several other classes that we would be going through to get to know the basics of File Navigation and I/O.

Directories in Java:

A directory is a File which can contains a list of other files and directories. You use File object to create directories, to list down files available in a directory. For complete detail check a list of all the methods which you can call on File object and what are related to directories.

Creating Directories:

There are two useful File utility methods, which can be used to create directories:

  • The mkdir( ) method creates a directory, returning true on success and false on failure. Failure indicates that the path specified in the File object already exists, or that the directory cannot be created because the entire path does not exist yet.

  • The mkdirs() method creates both a directory and all the parents of the directory.

Following example creates "/tmp/user/java/bin" directory:

 

    
package com.cv.java.file.io;

import java.io.File;

public class CreateDir {
   public static void main(String args[]) {
      String dirname = "/tmp/user/java/bin";
      File d = new File(dirname);
      // Create directory now.
      d.mkdirs();
  }
}

Compile and execute above code to create "/tmp/user/java/bin".

Note: Java automatically takes care of path separators on UNIX and Windows as per conventions. If you use a forward slash (/) on a Windows version of Java, the path will still resolve correctly.

Listing Directories:

You can use list( ) method provided by File object to list down all the files and directories available in a directory as follows:

 

    
package com.cv.java.file.io;

import java.io.File;

public class ReadDir {
   public static void main(String[] args) {
      
      File file = null;
      String[] paths;
            
      try{      
         // create new file object
         file = new File("/tmp");
                                 
         // array of files and directory
         paths = file.list();
            
         // for each name in the path array
         for(String path:paths)
         {
            // prints filename and directory name
            System.out.println(path);
         }
      }catch(Exception e){
         // if any error occurs
         e.printStackTrace();
      }
   }
}

This would produce following result based on the directories and files available in your /tmp directory:

test1.txt
test2.txt
ReadDir.java
ReadDir.class

Examples for File I/O Concepts :

 

    
/**
 
 */
package com.cv.java.file.io;

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

/**
 @author Chandra Vardhan
 *
 */
public class BufferedReaderFileExample {

  /**
   @param args
   */
  public static void main(String[] args) {
    File file = new File("kodam.txt");

    FileReader in = null;
    BufferedReader bufferedReader = null;
    
    try {
      in = new FileReader(file);

      bufferedReader = new BufferedReader(in);

      String string = bufferedReader.readLine();
      System.out.println("Output of the file : ");
      while (string != null) {
        System.out.println(string);
        string = bufferedReader.readLine();
      }
    catch (IOException e) {
      e.printStackTrace();
    finally {
      try {
        if(bufferedReader != null)
        bufferedReader.close();
      catch (IOException e) {
        e.printStackTrace();
      }
    }

  }

}


 

    
/**
 
 */
package com.cv.java.file.io;

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

/**
 @author Chandra Vardhan
 
 */
public class BufferedWriterFileExample {

  /**
   @param args
   */
  public static void main(String[] args) {
    BufferedWriter bufferedWriter = null;
    try {
      bufferedWriter = new BufferedWriter(new FileWriter(new File("kodam.txt")true));
      bufferedWriter.write(100);
      bufferedWriter.write('\n');
      bufferedWriter.write('u');
      bufferedWriter.newLine();
      char[] ch = 'a''b''c' };
      bufferedWriter.write(ch);
      bufferedWriter.newLine();
      bufferedWriter.write("chandravardhan");
      bufferedWriter.newLine();
      bufferedWriter.write("Technologies...");
      bufferedWriter.flush();
    catch (IOException e) {
      e.printStackTrace();
    finally {
      try {
        if (bufferedWriter != null) {
          bufferedWriter.close();
        }
      catch (IOException e) {
        e.printStackTrace();
      }
    }

  }

}


 

    
package com.cv.java.file.io;

import java.io.File;

import java.io.IOException;


/**
 @author Chandra Vardhan
 
 */
public class FileDemo {
  public static void main(String[] args)
  {
    File f=new File("abc.txt");
    System.out.println(f.exists());

    try {
      f.createNewFile();
    catch (IOException e) {
      e.printStackTrace();
    }
System.out.println(f.getAbsolutePath());
}
}


 

    
/**
 
 */
package com.cv.java.file.io;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

/**
 @author Chandra Vardhan
 *
 */
public class FileReaderAndWriterIO {

  /**
   @param args
   */
  public static void main(String[] args) {

    File fileName = new File("kodam.txt");
    try {
      FileReader fileReader = new FileReader(fileName);
      FileWriter fileWriter = new FileWriter("cv.txt");
      System.out.println(fileReader.read());
      char[] ch = new char[(intfileName.length()];
      int val = fileReader.read(ch);
      for (char c : ch) {
        System.out.print(c);
        fileWriter.write(c);
      }
      System.out.println(val);
      fileWriter.flush();
      fileReader.close();
      fileWriter.close();
    catch (FileNotFoundException e) {
      e.printStackTrace();
    catch (IOException e) {
      e.printStackTrace();
    }
  }

}


 

    
package com.cv.java.file.io;

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

/**
 @author Chandra Vardhan
 
 */
public class FileReaderDemo {
  public static void main(String[] argsthrows IOException {
    File f = new File("cv.txt");
    FileReader fr = new FileReader(f);
    char[] ch = new char[(intf.length()];
    fr.read(ch);
    for (char ch1 : ch) {
      System.out.println(ch1);
    }
    fr.close();

  }
}


 

    
package com.cv.java.file.io;

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

/**
 @author Chandra Vardhan
 
 */
public class FileReaderDemo1 {
  public static void main(String[] argsthrows IOException {
    File f = new File("cv.txt");
    FileReader fr = new FileReader(f);
    int i = fr.read();
    while (i != -1) {
      System.out.println((chari);
      i = fr.read();
    }
    fr.close();
  }
}


 

    
package com.cv.java.file.io;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;


/**
 @author Chandra Vardhan
 
 */
public class FileReaderIO {
    /**
     @param args
     */
    public static void main(String[] args) {
    
      File fileName = new File("cv.txt");
      try {
        FileReader fileReader = new FileReader(fileName);  
//        FileWriter fileWriter = new FileWriter("cho.doc");
//          System.out.println(fileReader.read());            
          int i = fileReader.read();
//          System.out.println("The value of i==="+i);
//          System.out.print((char)i);
//          long i2 = fileName.length();
//          System.out.println("The value of i2==="+i2);
          while(i != -1) {
            //System.out.print(i);          
            System.out.print((char)i);            
            i = fileReader.read();
          }
//          char[] ch = new char[(int) fileName.length()];      
//          int val = fileReader.read(ch);  
          
//          System.out.println(ch);
          /*for (char c : ch) {
            System.out.print(c);          
          }
          System.out.println(val);*/
        fileReader.close();  
        
      catch (FileNotFoundException e) {
        e.printStackTrace();
      }
      catch (IOException e) {
        e.printStackTrace();
      }
    }

  }


 

    
/**
 
 */
package com.cv.java.file.io;

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

/**
 @author Chandra Vardhan
 *
 */
public class IOFile {


  /**
   @param args
   @throws IOException
   */

  public static void main(String[] argsthrows IOException {

    File file = new File("cv.txt");

    System.out.println(file);


    System.out.println("canExecute" + file.canExecute());

    System.out.println("canRead" + file.canRead());

    System.out.println("canWrite" + file.canWrite());

    System.out.println("compareTo" + file.compareTo(new File("chote")));

    System.out.println("createNewFile" + file.createNewFile());

    /// System.out.println("delete"+file.delete());

    System.out.println("exists" + file.exists());

    System.out.println("getAbsolutePath" + file.getAbsolutePath());

    System.out.println("getCanonicalPath" + file.getCanonicalPath());

    System.out.println("getFreeSpace" + file.getFreeSpace());

    System.out.println("getName" + file.getName());

    System.out.println("getParent" + file.getParent());

    System.out.println("getPath" + file.getPath());

    System.out.println("getTotalSpace" + file.getTotalSpace());

    System.out.println("getUsableSpace" + file.getUsableSpace());

    System.out.println("isAbsolute" + file.isAbsolute());

    System.out.println("isDirectory" + file.isDirectory());

    System.out.println("isFile" + file.isFile());

    System.out.println("isHidden" + file.isHidden());

    System.out.println("lastModified" + file.lastModified());

    System.out.println("length" + file.length());

    // System.out.println("mkdir"+file.mkdir());

    // System.out.println("mkdirs"+file.mkdirs());

    System.out.println("renameTo" + file.renameTo(new File("dest.txt")));

    System.out.println("setExecutable" + file.setExecutable(true));

    System.out.println("setLastModified" + file.setLastModified(12 2001));

    System.out.println("setReadable" + file.setReadable(true));

    System.out.println("setReadOnly" + file.setReadOnly());

    System.out.println("setWritable" + file.setWritable(true));

    System.out.println("toString" + file.toString());

    System.out.println("getAbsoluteFile" + file.getAbsoluteFile());

    System.out.println("getCanonicalFile" + file.getCanonicalFile());

    System.out.println("getParentFile" + file.getParentFile());

    System.out.println("toURI" + file.toURI());

    System.out.println("pathSeparator" + File.pathSeparator);

    System.out.println("pathSeparatorChar" + File.pathSeparatorChar);

    System.out.println("separator" + File.separator);

    System.out.println("separatorChar" + File.separatorChar);

    System.out.println("=======================================");

    System.out.println("canExecute" + file.canExecute());

    System.out.println("canRead" + file.canRead());

    System.out.println("canWrite" + file.canWrite());

  }

}


 

    
/**
 
 */
package com.cv.java.file.io;

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

/**
 @author Chandra Vardhan
 *
 */
public class IOFileWriter {

  /**
   @param args
   */
  public static void main(String[] args) {

    try {
      FileWriter fileWriter = new FileWriter("cv.txt");
      char[] ch = 'j''y''o''t''i' };
      fileWriter.write(ch);
      fileWriter.write("chote");
      fileWriter.write("jyo");
      fileWriter.write("nav");
      fileWriter.write("dv");
      fileWriter.write(100);
      fileWriter.write('\n');
      fileWriter.write("nav\ndiv");
      fileWriter.flush();
      fileWriter.close();
      FileWriter fileWriter1 = new FileWriter("cv1.txt"true);
      // FileWriter fileWriter = new FileWriter(new
      // File("cvk.txt"),false);
      fileWriter1.write("chote");
      fileWriter1.write("cv");
      fileWriter1.write("kc");
      fileWriter1.write("vv");
      fileWriter1.write(100);
      fileWriter1.write('\n');
      fileWriter1.write("nav\ndiv");
      fileWriter1.flush();
      fileWriter1.close();
      FileWriter fileWrite = new FileWriter("cv2.txt");
      // FileWriter fileWriter = new FileWriter(new
      // File("cvk.txt"),false);
      fileWrite.write("chote");
      fileWrite.write("jyo");
      fileWrite.write("nav");
      fileWrite.write("dv");
      fileWrite.write(100);
      fileWrite.write('\n');
      fileWrite.write("nav\ndiv");
      fileWrite.flush();
      fileWrite.close();
      FileWriter fileWrite1 = new FileWriter("cv3.txt"true);
      // FileWriter fileWriter = new FileWriter(new
      // File("cvk.txt"),false);
      fileWrite1.write("chote");
      fileWrite1.write("cv");
      fileWrite1.write("kc");
      fileWrite1.write("vv");
      fileWrite1.write(100);
      fileWrite1.write('\n');
      fileWrite1.write("nav\ndiv");
      fileWrite1.flush();
      fileWrite1.close();
      FileWriter fileWriter2 = new FileWriter(new File("cv3.txt")true);
      // FileWriter fileWriter = new FileWriter(new
      // File("cvk.txt"),false);
      fileWriter2.write("chote");
      fileWriter2.write("jaanu");
      fileWriter2.write("hb");
      fileWriter2.write("divvv");
      fileWriter2.write(100);
      fileWriter2.write('\n');
      fileWriter2.write("nav\ndiv");
      fileWriter2.flush();
      fileWriter2.close();
      FileWriter fileWriter3 = new FileWriter(new File("cv4.txt")true);
      // FileWriter fileWriter = new FileWriter(new
      // File("cvk.txt"),false);
      fileWriter3.write("chote");
      fileWriter3.write("io");
      fileWriter3.write("jav");
      fileWriter3.write("kodam");
      fileWriter3.write(100);
      fileWriter3.write('\n');
      fileWriter3.write("nav\ndiv");
      fileWriter3.flush();
      fileWriter3.close();
    catch (IOException e) {
      e.printStackTrace();
    }

  }

}


 

    
package com.cv.java.file.io;

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

/**
 @author Chandra Vardhan
 
 */
public class MergeMultipleFilesWithPrintWriter {

  /**
   @param args
   */
  public static void main(String[] args) {
    // 
    PrintWriter printWriter = null;
    BufferedReader bufferedReader = null;
    BufferedReader  bufferedReader2 = null;
    try {
       printWriter = new PrintWriter("printWriter.txt");

       bufferedReader = new BufferedReader(new FileReader(
          "cv.txt"));

      String line = bufferedReader.readLine();

      while (line != null) {
        printWriter.println(line);
        line = bufferedReader.readLine();
      }
      

      bufferedReader2 = new BufferedReader(new FileReader("kodam.txt"));

      String line2 = bufferedReader2.readLine();

      while (line2 != null) {
        printWriter.println(line2);
        line2 = bufferedReader2.readLine();
      }
      
      printWriter.flush();
    
    catch (FileNotFoundException e) {
      e.printStackTrace();
    catch (IOException e) {
      e.printStackTrace();
    }catch (Exception e) {
      e.printStackTrace();
    finally {
      try {
        if(printWriter != null)
        printWriter.close();
        if(bufferedReader != null)
        bufferedReader.close();
        if(bufferedReader2 != null) {
          bufferedReader2.close();
        }
        
      catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
      
    }

  }

}


 

    
package com.cv.java.file.io;

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

/**
 @author Chandra Vardhan
 
 */
public class MergeMultipleFilesWithPrintWriter2 {
  /**
   @param args
   */
  public static void main(String[] args) {
    //  
    PrintWriter printWriter = null;
    BufferedReader bufferedReader = null;
    BufferedReader  bufferedReader2 = null;
    try {
       printWriter = new PrintWriter("printWriter2.txt");

       bufferedReader = new BufferedReader(new FileReader("kodam.txt"));

      String line = bufferedReader.readLine();

      bufferedReader2 = new BufferedReader(new FileReader("cv.txt"));

      String line2 = bufferedReader2.readLine();

      while ((line != null|| (line2 != null)) {
        if (line != null) {
          printWriter.println(line);
          line = bufferedReader.readLine();
        }
        if (line2 != null) {
          printWriter.println(line2);
          line2 = bufferedReader2.readLine();
        }
      }
      printWriter.flush();
        
    catch (FileNotFoundException e) {
      e.printStackTrace();
    catch (IOException e) {
      e.printStackTrace();
    }finally {
      try {
        if(printWriter != null)
        printWriter.close();
        if(bufferedReader != null)
        bufferedReader.close();
        if(bufferedReader2 != null) {
          bufferedReader2.close();
        }
        
      catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
      
    }

  }

}


 

    
/**
 
 */
package com.cv.java.file.io;

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

/**
 @author Chandra Vardhan
 
 */
public class MergeMultipleFilesWithPrintWriter3 {

  /**
   @param args
   */
  public static void main(String[] args) {
    // 
    PrintWriter printWriter = null;
    BufferedReader bufferedReader = null;
    BufferedReader  bufferedReader2 = null;
    try {
       printWriter = new PrintWriter("PrintWriter3.txt");

       bufferedReader = new BufferedReader(new FileReader(
          "cv.txt"));

      String line = bufferedReader.readLine();

      L1: 
        while (line != null) {

         bufferedReader2 = new BufferedReader(
            new FileReader("kodam.txt"));

        String target = bufferedReader2.readLine();

        while (target != null) {
          if (line.equals(target)) {
            line = bufferedReader.readLine();
            continue L1;
          }
          target = bufferedReader2.readLine();
        }
        printWriter.println(line);
        line = bufferedReader.readLine();
        bufferedReader2.close();
      }
      printWriter.flush();
      printWriter.close();
      bufferedReader.close();
    catch (FileNotFoundException e) {
      e.printStackTrace();
    catch (IOException e) {
      e.printStackTrace();
    }finally {
      try {
        if(printWriter != null)
        printWriter.close();
        if(bufferedReader != null)
        bufferedReader.close();
        if(bufferedReader2 != null) {
          bufferedReader2.close();
        }
        
      catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
      
    }

  }

}


 

    
/**
 
 */
package com.cv.java.file.io;

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

/**
 @author Chandra Vardhan
 
 */
public class MergeMultipleFilesWithPrintWriter4 {
  /**
   @param args
   */
  public static void main(String[] args) {
    //

    PrintWriter printWriter = null;
    BufferedReader bufferedReader = null;
    BufferedReader bufferedReader2 = null;
    try {
      printWriter = new PrintWriter("printWriter.txt");

      bufferedReader = new BufferedReader(new FileReader("cv.txt"));

      String line = bufferedReader.readLine();

      L1: while (line != null) {

        bufferedReader2 = new BufferedReader(new FileReader("kodam.txt"));

        // printWriter.println(line);
        String target = bufferedReader2.readLine();

        while (target != null) {
          if (line.equals(target)) {
            line = bufferedReader.readLine();
            continue L1;
          }
          target = bufferedReader2.readLine();
        }
        printWriter.println(line);
        line = bufferedReader.readLine();
        printWriter.flush();

      }

    catch (FileNotFoundException e) {
      e.printStackTrace();
    catch (IOException e) {
      e.printStackTrace();
    finally {
      try {
        if (printWriter != null)
          printWriter.close();
        if (bufferedReader != null)
          bufferedReader.close();
        if (bufferedReader2 != null) {
          bufferedReader2.close();
        }

      catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }

    }

  }

}


 

    
/**
 
 */
package com.cv.java.file.io;

import java.util.ArrayList;

/**
 @author Chandra Vardhan
 *
 */
public class MyStudent {

  /**
   @param args
   */
  public static void main(String[] args) {

    Student[] student = listOfStudents();

    for (Student student2 : student) {
      System.out.println(student2);
    }
  }

  public static Student[] listOfStudents() {

    Student student = new Student("jyo"22);
    Student student2 = new Student("cv"24);
    Student student3 = new Student("jyo"22);
    Student student4 = new Student("chote"25);

    ArrayList<Student> v = new ArrayList<Student>();

    v.add(student);
    v.add(student2);
    v.add(student3);
    v.add(student4);

    System.out.println(v.size());
    System.out.println(v.toArray(new Student[v.size()]));
    return (Student[]) (v.toArray(new Student[8]));
  }

}


 

    
/**
 
 */
package com.cv.java.file.io;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

/**
 @author Chandra Vardhan
 
 */
public class PrintWriterIOExample {

  /**
   @param args
   */
  public static void main(String[] args) {
    //

    PrintWriter printWriter = null;
    PrintWriter printWriter2 = null;
    PrintWriter printWriter3 = null;
    try {
      printWriter = new PrintWriter("cv1.txt");

      printWriter2 = new PrintWriter(new File("cv2.txt"));

      printWriter3 = new PrintWriter(new FileWriter("cv3.txt"));

      printWriter.write(100);
      printWriter.write(101);

      printWriter.println(100);
      printWriter.write("true");

      printWriter.println(true);
      printWriter.println('c');

      printWriter2.write(100);
      printWriter2.write(101);

      printWriter2.println(100);
      printWriter2.write("true");

      printWriter2.println(true);
      printWriter2.println('c');

      printWriter3.write(100);
      printWriter3.write(101);

      printWriter3.println(100);
      printWriter3.write("true");

      printWriter3.println(true);
      printWriter3.println('c');

      printWriter.flush();
      printWriter2.flush();
      printWriter3.flush();

    catch (FileNotFoundException e) {
      e.printStackTrace();
    catch (IOException e) {
      e.printStackTrace();
    finally {
      try {
        if (printWriter != null)
          printWriter.close();
        if (printWriter2 != null)
          printWriter2.close();
        if (printWriter3 != null)
          printWriter3.close();

      catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }

    }

  }

}


 

    
package com.cv.java.file.io;

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

public class ReadFromMultipleFilesAndWriteTo1File {

  public static void main(String[] args) {
    File directory = new File(
        "E:\\Technical_Stuff\\all_CoreJAva\\J2SEWorkspace\\copyJavaClassestoFile\\src\\com\\cv\\java\\file\\io2");
    StringBuffer sb = listFilesForFolder(directory);

    File changedFile = new File(
        "E:\\Technical_Stuff\\all_CoreJAva\\J2SEWorkspace\\copyJavaClassestoFile\\src\\com\\cv\\java\\file\\io2\\merge.txt");
    FileWriter fw;
    try {
      fw = new FileWriter(changedFile);
      BufferedWriter bw = new BufferedWriter(fw);
      bw.write(sb.toString());
      bw.close();
    catch (IOException e) {
      e.printStackTrace();
    }
  }

  public static StringBuffer readFile(final File filethrows IOException {
    String line = null;
    StringBuffer finalSB = new StringBuffer();
    if (file != null && file.exists() && file.isFile() && file.getName().endsWith(".txt")) {
      BufferedReader br = new BufferedReader(new FileReader(file));
      StringBuffer sb = new StringBuffer();
      while ((line = br.readLine()) != null) {
        String result = line;
        if (line != null) {
          sb.append(result);
        }
      }
      finalSB = sb;
      br.close();
    }
    return finalSB;
  }

  public static StringBuffer listFilesForFolder(final File folder) {
    StringBuffer sb = new StringBuffer();
    for (final File fileEntry : folder.listFiles()) {
      if (fileEntry.isDirectory()) {
        listFilesForFolder(fileEntry);
      else {
        try {
          sb.append(readFile(fileEntry));
        catch (IOException e) {
          e.printStackTrace();
        }
      }
    }
    return sb;
  }

}


 

    
/**
 
 */
package com.cv.java.file.io;

import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.Locale;

/**
 @author Chandra Vardhan
 
 */
public class Student {

  private String name;
  private int age;

  public Student() {

  }

  public Student(String name, int age) {

    this.name = name;
    this.age = age;

  }

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public int getAge() {
    return age;
  }

  public void setAge(int age) {
    this.age = age;
  }

  @Override
  public String toString() {
    return "Student [age=" + age + ", name=" + name + "]";
  }

  @Override
  public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result + age;
    result = prime * result + ((name == null: name.hashCode());
    return result;
  }

  //
  @Override
  public boolean equals(Object obj) {
    if (this == obj)
      return true;
    if (obj == null)
      return false;
    if (getClass() != obj.getClass())
      return false;
    Student other = (Studentobj;
    if (age != other.age)
      return false;
    if (name == null) {
      if (other.name != null)
        return false;
    else if (!name.equals(other.name))
      return false;
    return true;
  }

  public char charAt(int index) {
    return name.charAt(index);
  }

  public int codePointAt(int index) {
    return name.codePointAt(index);
  }

  public int codePointBefore(int index) {
    return name.codePointBefore(index);
  }

  public int codePointCount(int beginIndex, int endIndex) {
    return name.codePointCount(beginIndex, endIndex);
  }

  public int compareTo(String anotherString) {
    return name.compareTo(anotherString);
  }

  public int compareToIgnoreCase(String str) {
    return name.compareToIgnoreCase(str);
  }

  public String concat(String str) {
    return name.concat(str);
  }

  public boolean contains(CharSequence s) {
    return name.contains(s);
  }

  public boolean contentEquals(CharSequence cs) {
    return name.contentEquals(cs);
  }

  public boolean contentEquals(StringBuffer sb) {
    return name.contentEquals(sb);
  }

  public boolean endsWith(String suffix) {
    return name.endsWith(suffix);
  }

  public boolean equalsIgnoreCase(String anotherString) {
    return name.equalsIgnoreCase(anotherString);
  }

  public byte[] getBytes() {
    return name.getBytes();
  }

  public byte[] getBytes(Charset charset) {
    return name.getBytes(charset);
  }

  public byte[] getBytes(String charsetName)
      throws UnsupportedEncodingException {
    return name.getBytes(charsetName);
  }

  public void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin) {
    name.getChars(srcBegin, srcEnd, dst, dstBegin);
  }

  public int indexOf(int ch, int fromIndex) {
    return name.indexOf(ch, fromIndex);
  }

  public int indexOf(int ch) {
    return name.indexOf(ch);
  }

  public int indexOf(String str, int fromIndex) {
    return name.indexOf(str, fromIndex);
  }

  public int indexOf(String str) {
    return name.indexOf(str);
  }

  public String intern() {
    return name.intern();
  }

  public boolean isEmpty() {
    return name.isEmpty();
  }

  public int lastIndexOf(int ch, int fromIndex) {
    return name.lastIndexOf(ch, fromIndex);
  }

  public int lastIndexOf(int ch) {
    return name.lastIndexOf(ch);
  }

  public int lastIndexOf(String str, int fromIndex) {
    return name.lastIndexOf(str, fromIndex);
  }

  public int lastIndexOf(String str) {
    return name.lastIndexOf(str);
  }

  public int length() {
    return name.length();
  }

  public boolean matches(String regex) {
    return name.matches(regex);
  }

  public int offsetByCodePoints(int index, int codePointOffset) {
    return name.offsetByCodePoints(index, codePointOffset);
  }

  public boolean regionMatches(boolean ignoreCase, int toffset, String other,
      int ooffset, int len) {
    return name.regionMatches(ignoreCase, toffset, other, ooffset, len);
  }

  public boolean regionMatches(int toffset, String other, int ooffset, int len) {
    return name.regionMatches(toffset, other, ooffset, len);
  }

  public String replace(char oldChar, char newChar) {
    return name.replace(oldChar, newChar);
  }

  public String replace(CharSequence target, CharSequence replacement) {
    return name.replace(target, replacement);
  }

  public String replaceAll(String regex, String replacement) {
    return name.replaceAll(regex, replacement);
  }

  public String replaceFirst(String regex, String replacement) {
    return name.replaceFirst(regex, replacement);
  }

  public String[] split(String regex, int limit) {
    return name.split(regex, limit);
  }

  public String[] split(String regex) {
    return name.split(regex);
  }

  public boolean startsWith(String prefix, int toffset) {
    return name.startsWith(prefix, toffset);
  }

  public boolean startsWith(String prefix) {
    return name.startsWith(prefix);
  }

  public CharSequence subSequence(int beginIndex, int endIndex) {
    return name.subSequence(beginIndex, endIndex);
  }

  public String substring(int beginIndex, int endIndex) {
    return name.substring(beginIndex, endIndex);
  }

  public String substring(int beginIndex) {
    return name.substring(beginIndex);
  }

  public char[] toCharArray() {
    return name.toCharArray();
  }

  public String toLowerCase() {
    return name.toLowerCase();
  }

  public String toLowerCase(Locale locale) {
    return name.toLowerCase(locale);
  }

  public String toUpperCase() {
    return name.toUpperCase();
  }

  public String toUpperCase(Locale locale) {
    return name.toUpperCase(locale);
  }

  public String trim() {
    return name.trim();
  }

}

No comments:

Post a Comment