File handling questions
import
 java.io.*;
                // import java.lang.reflect.Array;
                import java.nio.file.Files;
                import java.nio.file.NoSuchFileException;
                import java.nio.file.Paths;
                import java.text.ParseException;
                import java.text.SimpleDateFormat;
                import org.joda.time.LocalDate;
                // import org.joda.time.DateTime;
                import org.joda.time.Period;
                import java.util.ArrayList;
                import java.util.Date;
                import java.util.Iterator;
                import java.util.Scanner;
                import java.util.regex.Matcher;
                import java.util.regex.Pattern;
                public class Donor implements Serializable {
                    String name, addr, contact, bldgrp;
                    Date date;
                    public static void main(String[] args) throws IOException {
                          // arraylist for retrieving and adding donors
                          ArrayList<Donor> ad = new ArrayList<Donor>();
                          int n, i; // counter variables
                          // format for date and time
                          SimpleDateFormat ft = new SimpleDateFormat("MM-dd-yyyy");
                          String temp;
                          // patten for blood group
                          String pattern = "[A|B|O|AB][+|-]";
                          Matcher m;
                          Pattern r = Pattern.compile(pattern);
                          // delete existing file first
                          try {
                              Files.deleteIfExists(Paths.get("donations.txt"));
                          } catch (NoSuchFileException e) {
                              System.out.println("Error: No such file/directory exists");
                          } catch (IOException e) {
                              System.out.println("Error: Invalid permissions.");
                          }
                          System.out.println("Success: Deletion successful.");
                          Scanner sc = new Scanner(System.in);
                          System.out.print("Enter number of donors: ");
                          n = sc.nextInt();
                          sc.nextLine();
                          Donor d;
                          System.out.println("----------------------");
                          for (i = 0; i < n; i++) {
                              d = new Donor(); // initializing new donor
                              // taking input from user
                              System.out.print("Name: ");
                              d.name = sc.nextLine();
         System.out.print("Address: ");
         d.addr = sc.nextLine();
         System.out.print("Contact: ");
         d.contact = sc.nextLine();
         d.bldgrp = "";
         m = r.matcher(d.bldgrp);
         while (!m.find()) {
              System.out.print("Blood Group (only A or B or O or AB [+|-] (all caps): ");
              d.bldgrp = sc.nextLine();
              m = r.matcher(d.bldgrp);
         }
         boolean flag = false;
         while (!flag) {
              System.out.print("Date (MM-dd-yyyy): ");
              temp = sc.nextLine();
              try {
                   d.date = ft.parse(temp);
                   flag = true;
              } catch (ParseException e) {
                   flag = false;
                   System.out.println("Unparseable using " + ft);
              }
         }
         // adding donor object to array list
         ad.add(d);
     }
     try {
         FileOutputStream fos = new FileOutputStream("donations.txt"); // creating file to write
to
         ObjectOutputStream oos = new ObjectOutputStream(fos);
         // serialization
         oos.writeObject(ad);
         oos.close();
         fos.close();
         System.out.println("Success: File successfully written");
     } catch (IOException ioe) {
         ioe.printStackTrace();
     }
     // reading data from file
     ad.clear();
     FileInputStream fis = new FileInputStream("donations.txt");
     ObjectInputStream ois = new ObjectInputStream(fis);
     try {
         ad = (ArrayList<Donor>) ois.readObject();
     } catch (ClassNotFoundException e) {
         System.out.println(e);
     }
     // defining current time and period
     LocalDate donor_date;
     LocalDate current = LocalDate.now();
     Period p;
     System.out.println("---------------------------------------------");
     System.out.println("---------------------------------------------");
     // iterating through the arraylist
     System.out.println("\n" + "Donors who haven't donated in 6 months and \"A+\"" + "\n");
     Iterator<Donor> itr = ad.iterator();
     i = 0;
     while (itr.hasNext()) {
         d = new Donor();
         d = (Donor) itr.next();
         donor_date = new LocalDate(d.date);
         p = new Period(donor_date, current);
                       // if more than 6 months and blood group is A+, print details
                       if ((p.getMonths() > 6 | p.getYears() >= 1) && d.bldgrp.equals("A+")) {
                           System.out.println("Donor " + (i + 1));
                           System.out.println("----------------------");
                           System.out.println(d.name); // name
                           System.out.println(d.addr); // address
                           System.out.println(d.contact); // contact
                           System.out.println(d.bldgrp); // blood group
                           System.out.println(d.date); // date
                           System.out.println("\n");
                       }
                   }
               }
           }
Write a Java Program that reads all data from a file and writes the data to another file. You have
to read and write data 1 byte at a time.
package javaprogrammingdemo;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.*;
public class javalabclass{
    public static void main(String args[]) throws IOException{
      try
      {
        //reading data from a file an writing to another file
        FileInputStream fin = new FileInputStream("satish.txt");
        FileOutputStream fout = new FileOutputStream("output.txt",true);
        int data;
        while((data=fin.read())!=-1)
        {
          fout.write(data);
        }
        System.out.println("File Write Completed");
        fin.close();
        fout.close();
      }
      catch(FileNotFoundException e)
      {
        System.out.println("Check File");
      }
      catch(Exception e)
      {
        System.out.println("Exception Occurred");
        e.printStackTrace();
      }
  }
}
package javalabdemo;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.Scanner;
public class javalabclass {
      public  static   void   main(String[]   args)  throws  InterruptedException,
FileNotFoundException, IOException, ClassNotFoundException {
    try
    {
    employee e[] = new employee[2];
    System.out.println("Enter the Employee Details");
    Scanner input = new Scanner(System.in);
    String name,empid,address,phone;
                 ObjectOutputStream    objout    =    new             ObjectOutputStream(new
FileOutputStream("satish.txt"));
    for(int i=0;i<e.length;i++)
    {
      System.out.println("Enter the employee name");
      name=input.nextLine();
      System.out.println("Enter the employee empid");
      empid=input.nextLine();
      System.out.println("Enter the employee address");
      address=input.nextLine();
      System.out.println("Enter the employee phone");
      phone = input.nextLine();
      e[i]=new employee(name,empid,address,phone);
      objout.writeObject(e[i]);
    }
    objout.writeObject(new endoffile());
    objout.close();
    //reading the objects from the input file
                   ObjectInputStream    objin    =     new   ObjectInputStream(new
FileInputStream("satish.txt"));
    Object obj = null;
      while((obj = objin.readObject()) instanceof endoffile == false){
                System.out.println(((employee)obj).name);}
    objin.close();
    }
    catch(Exception e)
    {
      System.out.println("I am catching exception here");
      System.out.println(e.getMessage());
    }
  }
}
class employee implements Serializable
{
  String name;
  String empid;
  String address;
  String phone;
  public employee(String name, String empid, String address, String phone) {
    this.name = name;
    this.empid = empid;
    this.address = address;
    this.phone = phone;
  }
}
class endoffile implements Serializable
{
Code to read data from the buffer after skipping a byte using BufferedInputStream
package practiceproject;
import java.io.*;
import java.util.*;
public class democlass {
public static void main(String[] args) throws IOException {
    File obj = new File("satish.txt");
    BufferedInputStream bin = new BufferedInputStream(new FileInputStream(obj));
    int data=bin.read();
    System.out.println(data);
    System.out.println(bin.skip(1));
    int data1=bin.read();
    System.out.println((char)data1);
}
}
Code for Writing numbers to two different files using Threads
package sampleproject;
import java.util.*;
import java.io.*;
public class democlass{
    public static void main(String[] args){
         filewrite1 f1 = new filewrite1();
         filewrite2 f2 = new filewrite2();
         f1.start();
         f2.start();
    }
}
class filewrite1 extends Thread
{
    @Override
    public void run() {
          File obj = new File("file1.txt");
          try {
          FileOutputStream fout = new FileOutputStream(obj);
          System.out.println("writing to file1");
          for(int i=0;i<10000;i++)
          {
            System.out.println("Thread1 write"+i);
            fout.write(i);
          }
          fout.close();
        } catch (FileNotFoundException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        } catch (IOException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
    }
}
class filewrite2 extends Thread
{
    @Override
    public void run() {
          File obj = new File("file2.txt");
          try {
          FileOutputStream fout1 = new FileOutputStream(obj);
          System.out.println("writing to file2");
          for(int i=0;i<10000;i++)
          {
            System.out.println("Thread2 write"+i);
            fout1.write(i);
          }
          fout1.close();
        } catch (FileNotFoundException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        } catch (IOException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
    }
}
package sampleproject;
import java.util.*;
import java.io.*;
public class democlass{
    public static void main(String[] args){
          filewrite1 f1 = new filewrite1();
        // filewrite2 f2 = new filewrite2();
          f1.start();
        // f2.start();
    }
}
class filewrite1 extends Thread
{
    @Override
    public void run() {
          File obj = new File("file1.txt");
          try {
          FileOutputStream fout = new FileOutputStream(obj);
          System.out.println("writing to file1");
          for(int i=0;i<10000;i++)
          {
            System.out.println("Thread1 write"+i);
            if(i==500)
            {
              System.out.println("thread sleep mode");
              filewrite1.sleep(6000);
            }
            fout.write(i);
          }
          fout.close();
        } catch (FileNotFoundException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        } catch (IOException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        } catch (InterruptedException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
    }
}
Problem 3:
Code for setting priority to Threads using the setPriority Method
package sampleproject;
import java.util.*;
import java.io.*;
public class democlass{
    public static void main(String[] args){
         filewrite1 f1 = new filewrite1();
         filewrite2 f2 = new filewrite2();
         f2.setPriority(10);
         f1.setPriority(1);
         f1.start();
         f2.start();
    }
}
class filewrite1 extends Thread
{
  @Override
  public void run() {
      byte b[]= {104,105,106,107,108,109,110,111,112,113,114,115};
      File obj = new File("file1.txt");
      try {
      FileOutputStream fout = new FileOutputStream(obj);
          System.out.println("writing to file1");
          fout.write(b);
          fout.close();
        } catch (FileNotFoundException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        } catch (IOException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
    }
}
class filewrite2 extends Thread
{
  @Override
  public void run() {
      byte b[]= {116,117};
      File obj = new File("file1.txt");
      try {
      FileOutputStream fout1 = new FileOutputStream(obj);
      System.out.println("writing to file2");
      fout1.write(b);
      fout1.close();
    } catch (FileNotFoundException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
}
To count number of words
 1package com.javaonline;
 2 
 3import java.util.*;
 4import java.io.*;
 5public class CountWordsInFile {
 6    public static void main(String[] args) throws IOException {
 7try
 8{
 9 
 1    String fileName="myFile.txt";
 0 
 1    FileWriter file = new FileWriter(fileName);
 1    file.write("This program counts the number of words and lines in a file.\n Scanner class is used to read the
 1delimiter.");
 2    file.close();
 1 
 3     int count =0;
 1      Scanner sc = new Scanner(new File(fileName));
 4 
 1 //To count words     
 5 
 1      while (sc.hasNext())
 6          {
 1          count++;
 7          sc.next();
 1           }
 8 
 1      System.out.println("No of Words in the given file ( " + fileName + " ) : "  + count);
 9 
 2      sc = new Scanner(new File(fileName));
 0 
 2   // To count lines
 1    //sc.useDelimiter("\n"); //to set new line as delimiter
 2     // sc.reset(); to use the default delimiter
 2     count=0;
 2
 3
 2
 4
 2
 5
 2
 6
 2
 7
 2
 8
 2
 9
 3
 0
 3
 1
 3
 2
 3
 3
 3
 4
 3
 5
 3
 6
 3
 7
 3
 8
 3
 9
 4
 0
 4
 1
 4
 2
 4
 3
 4
 4     while( sc.hasNextLine())
 4     {
 5         count++;
 4         sc.nextLine();
 6 
 4     }
 7 
 4     System.out.println("No of Lines in the given file ( " + fileName + " ) : "  + count);
 8 
 4      sc.close();
 9 
 5}
 0catch (FileNotFoundException e)
 5{
 1    System.out.println("The given file "+ fileName + "  not found ");
 5}
 2 
 5    }
 3}
import java.io.*;
  
public class Test {
    public static void main(String[] args)
        throws IOException
    {
        File file = new File("C:\\Users\\hp\\Desktop\\TextReader.txt");
        FileInputStream fileInputStream = new FileInputStream(file);
        InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream);
        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
  
        String line;
        int wordCount = 0;
        int characterCount = 0;
        int paraCount = 0;
        int whiteSpaceCount = 0;
        int sentenceCount = 0;
  
        while ((line = bufferedReader.readLine()) != null) {
            if (line.equals("")) {
                paraCount += 1;
            }
            else {
                characterCount += line.length();
                String words[] = line.split("\\s+");
                wordCount += words.length;
                whiteSpaceCount += wordCount - 1;
                String sentence[] = line.split("[!?.:]+");
                sentenceCount += sentence.length;
            }
        }
        if (sentenceCount >= 1) {
            paraCount++;
        }
        System.out.println("Total word count = "+ wordCount);
        System.out.println("Total number of sentences = "+ sentenceCount);
        System.out.println("Total number of characters = "+ characterCount);
        System.out.println("Number of paragraphs = "+ paraCount);
        System.out.println("Total number of whitespaces = "+ whiteSpaceCount);
    }
}
Write and Read an Integer, String and Booolean value using a File. Use dataInputStream and
dataOutputStream for the file operations
package practiceproject;
import java.io.*;
import java.util.*;
public class democlass {
      public static void main(String[] args) throws IOException {
            File obj = new File("satish1.txt");
            FileOutputStream fout = new FileOutputStream(obj);
            DataOutputStream dout = new DataOutputStream(fout);
            dout.write(2);
            dout.writeUTF("satish");
            dout.writeBoolean(true);
            System.out.println("File writing successful");
            fout.close();
            dout.close();
            DataInputStream din = new DataInputStream(new FileInputStream(obj));
            int data=din.read();
            String name = din.readUTF();
            boolean result=din.readBoolean();
            System.out.println(data);
            System.out.println(name);
            System.out.println(result);
      }
}
    1. import java.io.*;  
    2. class PipedWR{  
    3. public static void main(String args[])throws Exception{  
    4. final PipedOutputStream pout=new PipedOutputStream();  
    5. final PipedInputStream pin=new PipedInputStream();  
    6.   
7. pout.connect(pin);//connecting the streams  
8. //creating one thread t1 which writes the data  
9. Thread t1=new Thread(){  
10. public void run(){  
11. for(int i=65;i<=90;i++){  
12. try{  
13. pout.write(i);  
14. Thread.sleep(1000);  
15. }catch(Exception e){}  
16. }  
17. }  
18. };  
19. //creating another thread t2 which reads the data  
20. Thread t2=new Thread(){  
21. public void run(){  
22. try{   
23. for(int i=65;i<=90;i++)  
24. System.out.println(pin.read());  
25. }catch(Exception e){}  
26. }  
27. };  
28. //starting both threads  
29. t1.start();  
30. t2.start();  
31. }}  
32. class InvalidAgeException  extends Exception  
33. {  
34.     public InvalidAgeException (String str)  
35.     {  
36.         // calling the constructor of parent Exception  
37.         super(str);  
38.     }  
39. }  
40.     
41. // class that uses custom exception InvalidAgeException  
42. public class TestCustomException1  
43. {  
44.   
45.     // method to check the age  
46.     static void validate (int age) throws InvalidAgeException{    
47.        if(age < 18){  
48.   
49.         // throw an object of user defined exception  
50.         throw new InvalidAgeException("age is not valid to vote");    
51.     }  
52.        else {   
53.         System.out.println("welcome to vote");   
54.         }   
55.      }    
56.   
57.     // main method  
58.     public static void main(String args[])  
59.     {  
60.         try  
61.         {  
62.             // calling the method   
63.             validate(13);  
64.         }  
65.         catch (InvalidAgeException ex)  
66.         {  
67.             System.out.println("Caught the exception");  
68.     
69.             // printing the message from InvalidAgeException object  
70.             System.out.println("Exception occured: " + ex);  
71.         }  
72.   
73.         System.out.println("rest of the code...");    
74.     }  
75. }