2 Write a program which will open an input file and write to

2. Write a program which will open an input file and write to an output file. Use exception handling (try & Catch to display appropriate error handling).

Solution

herer is code:

import java.io.*;
public class Copytxt{
public static void main (String[] args)throws IOException {
int i;
FileInputStream fin;
FileOutputStream fout;
try {
// open input file
try {
fin = new FileInputStream(\"input.txt\"); // pass the input location file here
}
catch (FileNotFoundException e) { // if file not found
System.out.println(\"Input File Not Found\");
return;
}
// open output file
try {
fout = new FileOutputStream(\"output.txt\"); // pass the output location file here
}
catch (FileNotFoundException e) { // if file not found
System.out.println(\"Error Opening Output File\");
return;
}
}
catch (ArrayIndexOutOfBoundsException e) {
System.out.println(\"Usage: CopyFile From To\");
return;
}
// Copy File
try {
       byte[] buffer = new byte[1024];

   int length;
   /*copying the contents from input stream to
   * output stream using read and write methods
   */
   while ((length = fin.read(buffer)) > 0){
       fout.write(buffer, 0, length);
   }
}
catch (IOException e) {
System.out.println(\"File Error\");
}
fin.close();
fout.close();
}
}

2. Write a program which will open an input file and write to an output file. Use exception handling (try & Catch to display appropriate error handling).Sol

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site