Problem 6 (11 points, adapted from Sehilde\'s book page 431): Rewrite the follow
ID: 3903350 • Letter: P
Question
Problem 6 (11 points, adapted from Sehilde's book page 431): Rewrite the following program so that it uses try-with-resources to eliminate the calls to close0. Use only one try block. import javaio. class NoTryWithResources ( public static void main(Stringll args) t FilelnputStream fin-null; FileOutputStream fout- null: // First make sure that both files have specified. if(args.length ! 2) f System.out printla"Usage: NoTryWithResources From Tor return try f fin-new FilelnputStream(args[OD: System.out.printin"IOException: program halted.- fout = new FileOutputStream(args(11); System.out.printin"IOException: program halted."); ifffin !-null && fout!-null) catch (IOException exc) f catch (IOException exc) try f int c fin.readO: fout.write(c); catch (IOException exc) System.out.println"IOException: program halted.") finally f try t if fin!- null) fin.closeO; catch (IOException exc) System.out.printin "IOException: program halted.") try f if(fout!- null) fout.close0: catch (IOException exc) t System.out.printin"1OException: program halted.");Explanation / Answer
Below is the solution:
code NoTryWithResources.java:
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class NoTryWithResources {
public static void main(String[] args) {
FileInputStream fin = null; //create fileinput stream variable with null
FileOutputStream fout =null; //create fileoutput stream variable with null
if(args.length !=2) { //check if the argument length is not equal to 2
System.out.println("Usage: NoTryWithResources from to");
return;
}
try {
fin = new FileInputStream(args[0]); //input argument first
fout = new FileOutputStream(args[1]); //output argument second
if(fin !=null && fout !=null) { //check both are not null
int c = fin.read(); //read the input file
fout.write(c); //write the output file
}
}
catch(IOException exc) { //error when file not found
System.out.println("IOException: program halted.");
}
//finall block will always execute and close the file which are input and output
finally {
try {
if(fin!=null) {
fin.close();
}
if(fout!=null) {
fout.close();
}
}
catch(IOException exc) {
System.out.println("IOException: program halted.");
}
}
}
}
sample output:
story.txt:
You can search.
story1.txt:
Y