File Handling Questions
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;
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;
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
Code to read data from the buffer after skipping a byte using BufferedInputStream
package practiceproject;
import java.io.*;
import java.util.*;
public class democlass {
}
}
Code for Writing numbers to two different files using Threads
package sampleproject;
import java.util.*;
import java.io.*;
public class democlass{
@Override
public void run() {
@Override
public void run() {
@Override
public void run() {
Problem 3:
Code for setting priority to Threads using the setPriority Method
package sampleproject;
import java.util.*;
import java.io.*;
public class democlass{
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 {
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. }