1) There is no criterion for determining the size of your byte array. In this code, it used 32 kbytes, but you can use any value. The size of the byte array and the size of your file determine how many times you will read the file, more buffers lead to fewer read requests, but not necessary if you are working with small files.
2) Whenever you use a method in Java that can throw an exception, you need to catch that exception and do something with it. You can handle the exception in your code (usually print a stack trace for debugging purposes) or throw it, which means that when someone uses your code, you need to catch the exception of your code.
3) What he did was to catch two possible exceptions and indicate what was happening. Since FileNotFoundException extends an IOException , it can just use one try and catch only an IOException , it encoded this method to find out if the IOException FileNotFoundException or any other IOException . Personally, I will not write code in the same way as the author did, it is easy to read.
Rewriting the code may make it easier to understand attempts and traps:
System.out.println("Copying files with streams."); InputStream inStream = null; OutputStream outStream = null; try { inStream = new BufferedInputStream(new FileInputStream(aSourceFile)); outStream = new BufferedOutputStream(new FileOutputStream(aTargetFile, aAppend)); } catch (FileNotFoundException ex){ // TODO Handle FileNotFoundException ex.printStackTrace(); } try { byte[] bucket = new byte[32*1024]; int bytesRead = 0; while(bytesRead != -1){ bytesRead = inStream.read(bucket); //-1, 0, or more outStream.write(bucket, 0, bytesRead); } } catch (IOException ex){ // TODO Handle IOException ex.printStackTrace(); } finally { try { if (inStream != null) inStream.close(); if (outStream != null) outStream.close(); } catch (IOException ex){ // TODO Handle IOException ex.printStackTrace(); } }
He does the same.
source share