The following example shows how to copy file using streams.
private void copyWithStreams(File aSourceFile, File aTargetFile, boolean aAppend) {
log("Copying files with streams.");
ensureTargetDirectoryExists(aTargetFile.getParentFile());
InputStream inStream = null;
OutputStream outStream = null;
try{
try {
byte[] bucket = new byte[32*1024];
inStream = new BufferedInputStream(new FileInputStream(aSourceFile));
outStream = new BufferedOutputStream(new FileOutputStream(aTargetFile, aAppend));
int bytesRead = 0;
while(bytesRead != -1){
bytesRead = inStream.read(bucket); //-1, 0, or more
if(bytesRead > 0){
outStream.write(bucket, 0, bytesRead);
}
}
}
finally {
if (inStream != null) inStream.close();
if (outStream != null) outStream.close();
}
}
catch (FileNotFoundException ex){
log("File not found: " + ex);
}
catch (IOException ex){
log(ex);
}
}
private void ensureTargetDirectoryExists(File aTargetDir){
if(!aTargetDir.exists()){
aTargetDir.mkdirs();
}
}
private static void log(Object aThing){
System.out.println(String.valueOf(aThing));
}
For the above code snippet, I feel confused about four points:
1) Bucket is allocated as byte[] bucket = new byte[32*1024]; Is there any criterion for choosing the size, such as 32*1024
2) Why it has to “catch” here? Is there any rule for including catch in writing program?
3) I am also not very clear about the usage of “try” here. It seems the author uses nested try in this program.
1) There isn’t a criterion to define the size of your byte array. In the given code it’s used 32 kbytes but you could use any value. The size of the byte array and the size of your file determinate how many times you’ll read the file, bigger buffers results in less reading calls, but aren’t necessary if you’re working with small files.
2) Whenever you use an method in Java that can throws an exception, you need to catch that exception and do something with it. You can treat the exception in your code (usually print the stack trace to debugging purposes) or throw it, which means that when someone use your code will need to catch your code’s exception.
3) What he did was to catch the two possible exceptions and specifies which one occurs. Since
FileNotFoundExceptionextendsIOExceptionhe could simply use one try, and catch only theIOException, he coded that way to know if theIOExceptionis aFileNotFoundExceptionor any otherIOException. Personally, I wouldn’t write the code the same way the author did, it isn’t easily readable.Maybe rewriting the code it gets easier to you understand the tries and catchs:
It does the same stuff.