Files in Java

1.Program to copy bytes from one file into another

import java.io.*;
class copybytes
{
  public static void main(String []args)
  {
    FileInputStream infile=null;
    FileOutputStream outfile=null;
    int b;
    try
    {
      infile=new FileInputStream("City.txt");
      outfile=new FileOutputStream("City copy.txt");
      while((b=infile.read())!=-1)
      {
        outfile.write(b);
       }
    }
    catch(FileNotFoundException e)
    {
      System.out.println("File not Found");
    }
      catch(IOException ioe)
      {
        System.out.println(ioe);
        System.exit(-1);
      }
      finally
      {
        try
        {
          infile.close();
          outfile.close();
         
        }
        catch(IOException e){}
      }
    }
  }

2.Program to list the files and subdirectories inside a directory

import java.io.*;
class MyDir{
  public static void main(String []args){
  File f=new File("C:\\MyDir");
  if(f.isDirectory()){
  String list[]=f.list();
  for(int i=0;i<list.length;i++)
  {
    System.out.println(list [i]);
  }
  for(int j=0;j<list.length;j++)
  {
    File f1=new File("C:\\MyDir"+"\\"+list [j]);
 
  System.out.println("Is File"+list[j]+"directory?" +f1.isDirectory());
   
  }
 
  }

3.Program to filter the files of the directory by implementing FilenameFilter interface

import java.io.*;
class MyFilt implements FilenameFilter
{
  public boolean accept(File dir,String name){
  return name.endsWith("*.html");
  }
}

class MyDir2{
  public static void main(String []args){
  File f=new File("C:\\MyDir");
  FilenameFilter ht=new MyFilt();
  String list[]=f.list(ht);
  for(int i=0;i<list.length;i++){
  System.out.println(list[i]);
  }
  }
}


4. Writing to a file using ByteArray Output Stream

import java.io.*;
class MyB{
  public static void main(String []args)throws Exception{
  ByteArrayOutputStream f=new ByteArrayOutputStream(10);
  while(f.size()!=5){
  f.write((System.in.read()));
  }
  System.out.println(f.toString());
  OutputStream f1=new FileOutputStream("MyFile.txt");
  f.writeTo(f1);
  }

}

5.Use of Byte array input stream

import java.io.*;
class MyByte{
  public static void main(String []args){
  String s="My ByteArrayInputStream";
  byte []mystr=s.getBytes();
  ByteArrayInputStream in=new ByteArrayInputStream(mystr);
  int r;
  while((r=in.read())!=-1){
  System.out.println((char)r);
  }
  }
}

6.Creat a file using class 'File'

import java.io.*;
class MyFile{
public static void main(String []args)
{
  File  f=new File("C:\\","bikal.dat");
  System.out.println("File name:" + f.getName());
  System.out.println("Existance:" + f.exists());
  System.out.println("Is Writable:"+ f.canWrite());
}
}

7.To display the size of file

import java.io.*;
class MyIn{
  public static void main(String [] args)throws Exception{
  InputStream f=new FileInputStream("C:\\MyDir\\Vector.java");
  System.out.println("Size="+f.available());//gives the available size in the file
  System.out.println((char)f.read());//reads first character from the file
  f.skip(1);//skips reading a character
  System.out.println("Size2="+f.available());
  System.out.println((char)f.read());
  System.out.println("Size3="+f.available());
  f.close();
  }
}


8.Write the data to the file using Filewriter

import java.io.*;
class MyWriter{
  public static void main(String []args)throws Exception{
  FileReader f0=new FileReader("C:\\MyDir\\writer.txt");
  BufferedReader b=new BufferedReader(f0);
  FileWriter f=new FileWriter("C:\\MyDir\\bkl.txt");
  String str;
  while((str=b.readLine())!=null){
  f.write(str);
  }
  f.close();
  f0.close();
  }

}

9.Program to read data from user and write into file till user press return key

/*
 Reader
 Writer
*/
import java.io.*;
class MyReader{
  public static void main(String []args)throws Exception{
  FileReader f=new FileReader("C:\\MyDir\\writer.txt");
  BufferedReader b=new BufferedReader(f);
  //System.out.println(b.readLine());//Displays first line of the file
  String str;
  while((str=b.readLine())!=null){
    System.out.println(str);
  }
  }
}


10.Complete File I/O operation in Java.

/**
 *Programmer: Bikal Adhikari
 * Program:To write,read and modify a file with the record of students containing fields name
 *         roll number,marks,address.The no. of students is provided by the user.
 * Designation:Student
 * Compiled on: Eclipse IDE under Ubuntu 12.10
 */

import java.io.*;//imports classes of java.io package
import java.util.Scanner;//imports class Scanner
import java.lang.*;
import java.util.ArrayList;


class fileIO{
  int roll;
  float marks;
  String name,address;


  public void getData(){//To get input data from user
  Scanner in=new Scanner(System.in);
  System.out.println("Enter Name:");name=in.next();
  System.out.println("Enter Roll Number:");roll=in.nextInt();
  System.out.println("Enter Marks:");marks=in.nextFloat();
  System.out.println("Enter Address:");address=in.next();
  }


  public void writer(String st)throws Exception{ //To write the data entered by the user into a file
  FileWriter outfile=new FileWriter(st);//creates a filewriter objects and calls the parameterized constructor with file name.
  Scanner in1=new Scanner(System.in);//Creates a Scanner object in1
  fileIO fs=new fileIO();//Creates a fileIO object
  System.out.println("Enter the number of Students:");
  int n=in1.nextInt();//Takes input from user and assigns it to n
  for(int j=1;j<=n;j++){
  fs.getData();//Input records of students
  String str=fs.name+" "+fs.roll+" "+
              fs.marks+" "+fs.address;//Concatenates all user record field into single string object
    outfile.write(str+"\r\n");//writes string into the file using filewriter object
      }
  System.out.println("File Written:");
  outfile.close();//close the filewriter stream
  }



  public void reader(String st)throws Exception{ //To read the contents of a file
  System.out.println("Lets' read file:");
  FileReader infile=new FileReader(st);//creates a filereader objects and calls the parameterized constructor with file name.
  BufferedReader b=new BufferedReader(infile);//Creates a bufferedreader object to use method readLine()
  String str;
  System.out.println("Name"+" "+"Roll"+" "+
              "Marks"+" "+"Address");
  while((str=b.readLine())!=null)//Reads the string from file line by line
   System.out.println(str);//and display it in console
  infile.close();

  }


  public void total_size(String st)throws Exception{//To determine the no. of Students in file and total file size
  System.out.println("Lets' find the total no. of students and size of the file:");
  FileReader infile=new FileReader(st);
  File file=new File(st);
  BufferedReader b=new BufferedReader(infile);
  int c=0;
  while((b.readLine())!=null){
  ++c;//Every line of file read corresponds to a increment in the number of students inside the file
  }
  System.out.println("The total number of students is:"+c);
  System.out.println("The total file size in bytes is:"+file.length()+" Bytes.");//File object "file" uses method length() to determine the size of file in bytes.
  infile.close();
  }


   public void addRecord(String st)throws Exception{ //To add a record into the file
   FileWriter outfile=new FileWriter(st,true);//creates a filewriter objects and calls the parameterized constructor with file name.
   fileIO fs=new fileIO();//Creates a fileIO object
   fs.getData();//Input record of a students to be added
   String str=fs.name+" "+fs.roll+" "+
              fs.marks+" "+fs.address;//Concatenates all user record field into single string object
 
   outfile.write(str+"\r\n");
   outfile.close();
   System.out.println("Record Added:");
   outfile.close();//close the filewriter stream
   System.out.println("The updated file is as follows:");
   reader(st);
   }


   public void findRecord(String st)throws Exception{
   System.out.println("Enter the roll number of student to be searched:");
   Scanner inn=new Scanner(System.in);
   String bkl=Integer.toString(inn.nextInt());
   FileReader infile=new FileReader(st);//creates a filereader objects and calls the parameterized constructor with file name.
   BufferedReader b=new BufferedReader(infile);//Creates a bufferedreader object to use method readLine()
   String str;
   try{
   while((str=b.readLine())!=null)//Reads the string from file line by line
   {
         String []tokens=str.split(" ");
         String []dis={"Name:","Roll:","Marks:","Address:"};
         if((bkl.compareTo(tokens[1]))==0){
         System.out.println("Record Found:");
         for(int k=0;k<tokens.length;k++){
         System.out.println(dis[k]+tokens[k]);
         }    
     }
   }
   }
   catch(IOException e){}
   catch(NullPointerException e){System.out.println("Null pointer Exception has occured.");}
   infile.close();
   }
 
 
 
 
 
   public void modifyRecord(String st)throws Exception{
   System.out.println("Enter the roll number of student to be modified:");
   Scanner inn=new Scanner(System.in);
   String bkl=Integer.toString(inn.nextInt());
   FileReader infile=new FileReader(st);//creates a filereader objects and calls the parameterized constructor with file name.
   BufferedReader b=new BufferedReader(infile);//Creates a bufferedreader object to use method readLine()
   fileIO fs=new fileIO();
   String str;
   int c=0;
   ArrayList <String> strclone=new ArrayList <String> ();
   System.out.println("Enter the modified data of the record:");
 
   while((str=b.readLine())!=null)//Reads the string from file line by line
   {
       
         strclone.add(str);
   }
   for(int n=0;n<strclone.size();n++){
   String []tokens=strclone.get(n).split(" ");
   if((bkl.compareTo(tokens[1]))==0){
     c=1;
     fs.getData();
     strclone.remove(n);
     strclone.add(n,fs.name+" "+fs.roll+" "+
              fs.marks+" "+fs.address);
     break;
   }
     }
   infile.close();
   if(c!=1)
   {
     ExitonException();
   }

   FileWriter outfile=new FileWriter(st);
   for(int j=0;j<strclone.size();j++){
   outfile.write(strclone.get(j)+"\r\n");
   }
   outfile.close();
   System.out.println("Record modified:");
   reader(st);
 
   }
 
     void ExitonException(){
     System.out.println("Sorry record doesnt exists");
     System.exit(1);
   }
 
 
 


    public static void main(String []args)throws Exception{
    Scanner in2=new Scanner(System.in);
    fileIO bkl=new fileIO();
    System.out.println("Enter file name with complete path:");//prompts user to enter the file path
    String str=in2.next();//inputs the file path and assigns it to String object str
 
    System.out.println("Enter what do you want to do?");
    System.out.println("1.Write to the file?");
    System.out.println("2.Read the file?");
    System.out.println("3.Add the record into the file");
    System.out.println("4.To search a record of a student with roll number as a key.");
    System.out.println("5.To modify a record of a student with roll number as a key.");
    System.out.println("6.To calculate no. of objects and size of the file.");  
    int n=in2.nextInt();
 
 
    switch(n)//To select a choice entered by the user.
    {
   
      case 1:{
      System.out.println("You have chosen to write the file.");
      bkl.writer(str);
      break;
      }
   
   
      case 2:{
      System.out.println("You have chosen to read the file.");
      bkl.reader(str);
      break;
      }
   
      case 3:{
      System.out.println("You have chosen to add the record into the file.");
      bkl.addRecord(str);
      break;
      }
   
   
   
       case 4:{
      System.out.println("You have chosen to search the record of a student.");
      bkl.findRecord(str);
      break;
      }
     
     
     
     
       case 5:{
      System.out.println("You have chosen to modify the record of a student.");
      bkl.modifyRecord(str);
      break;
      }
   
   
   
   
   
      case 6:{
      System.out.println("You have chosen to calculate no. of objects and size of the file.");
      bkl.total_size(str);
      break;
      }
   
   
      default:{
      System.out.println("Wrong Choice!");
    }
    }//switch closed
 
 
}//main function closed
}//Class fileIO closed

0 comments:

Post a Comment