Problem 6 (11 points, adapted from Schildt\'s book page 431): Rewrite the follow
ID: 3735792 • Letter: P
Question
Problem 6 (11 points, adapted from Schildt's book page 431): Rewrite the following program so that it uses try-with-resources to eliminate the calls to closeO. Use only one try block. import javajo. class NoTryWithResources public static void main(Stringl] args) FileInputStream fin- null: FileOutputStream fout nll; l First make sure that both files have specified if args.length ! 2) f ystem.out,printin"Usage: NoTry WithResources From To" return; try f catch (IOException exc) f try f catch (IOException exc) ( fin - new File nputStream(args[OD System.out.printin"IOException: program halted."); fout - new FileOutputStream(args1D) System.out.printin"IOException: program halted.'"); iffin-null&&fout;!-null) try f int c -fin.readO; fout.write(c); catch (IOException exc) System.out. finally f ifin !null) fin.close0 catch (IOException exc) f System.out.printin"1OException: program halted.") try ( if(fout ! null) fout close0: catch (IOException exc)t System.out,printin"1OException: program halted.")Explanation / Answer
Given below is the modified code as per the specifications.
import java.io.*;
public class NoTryWithResources {
public static void main(String[] args) {
if(args.length != 2)
{
System.out.println("Usage: NoTryWithResources From To");
return;
}
try(FileInputStream fin = new FileInputStream(args[0]);
FileOutputStream fout = new FileOutputStream(args[1]);)
{
int c = fin.read();
fout.write(c);
} catch (IOException e) {
System.out.println("IOException: program halted.");
}
}
}