0

I am trying to copy files using BufferedInputStream, and this error occurred when compile:

BufferedByteStreamCopy2.java:22: error: unreported exception IOException; must be caught or declared to be thrown bin.close(); ^ BufferedByteStreamCopy2.java:24: error: unreported exception IOException; must be caught or declared to be thrown bout.close(); ^

Could you help me to explain this? How can I modify the code? Many thanks!

import java.io.*;
public class BufferedByteStreamCopy2 {
  public static void main(String[] args) {
    BufferedInputStream bin = null;
    BufferedOutputStream bout = null;
  try {
    FileInputStream fin = new FileInputStream(args[0]);
    bin = new BufferedInputStream(fin);
    FileOutputStream fout = new FileOutputStream(args[1]);
    bout = new BufferedOutputStream(fout);
    int c;
    while ((c = bin.read()) != -1)
    bout.write(c);
 } catch (ArrayIndexOutOfBoundsException e) {
  System.out.println("Not enough parameter.");
 } catch (FileNotFoundException e) {
  System.out.println("Could not open the file:" + args[0]);
 } catch (Exception e) {
  System.out.println("ERROR copying file");
 } finally {
   if (bin != null)
      bin.close();
   if (bout != null)
      bout.close();
 }

} }

1
  • The code you've provided compiles fine. Given the name of your public class and the filename reported in the error, are you sure this isn't just a matter of having two copies of your source code - one working and one broken? Commented Mar 29, 2014 at 7:57

1 Answer 1

0

try/catch will catch an Exception but this doesn't apply to an exception thrown in a finally block. You need a try catch for the close() in there as well.

Note: copying a byte at a time is pretty inefficient, I assume this is just an exercise. As @EJP point out there is more read() and write() methods.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you Peter! Sorry for the confusion..Here is the edited post with ButteredByteStreamCopy2Java. Exactly like you said it is an exercise. Although I don't really know a more efficient way.
@user3474606 You had it right the first time, with a try/catch block inside the exception handler. The issue of one byte at a time isn't major given you're using buffered streams, but there are other read() methods. Look them up.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.