Java Reference
In-Depth Information
Example 3−2: FileCopy.java (continued)
BufferedReader in=
new BufferedReader(new InputStreamReader(System.in));
String response = in.readLine();
// Check the response. If not a Yes, abort the copy.
if (!response.equals("Y") && !response.equals("y"))
abort("existing file was not overwritten.");
}
else {
// If file doesn't exist, check if directory exists and is
// writeable. If getParent() returns null, then the directory is
// the current dir. so look up the user.dir system property to
// find out what that is.
String parent = to_file.getParent(); // The destination directory
if (parent == null) // If none, use the current directory
parent = System.getProperty("user.dir");
File dir = new File(parent);
// Convert it to a file.
if (!dir.exists())
abort("destination directory doesn't exist: "+parent);
if (dir.isFile())
abort("destination is not a directory: " + parent);
if (!dir.canWrite())
abort("destination directory is unwriteable: " + parent);
}
// If we've gotten this far, then everything is okay.
// So we copy the file, a buffer of bytes at a time.
FileInputStream from = null; // Stream to read from source
FileOutputStream to = null;
// Stream to write to destination
try {
from = new FileInputStream(from_file); // Create input stream
to = new FileOutputStream(to_file);
// Create output stream
byte[] buffer = new byte[4096];
// To hold file contents
int bytes_read;
// How many bytes in buffer
// Read a chunk of bytes into the buffer, then write them out,
// looping until we reach the end of the file (when read() returns
// -1). Note the combination of assignment and comparison in this
// while loop. This is a common I/O programming idiom.
while((bytes_read = from.read(buffer)) != -1) // Read until EOF
to.write(buffer, 0, bytes_read);
// write
}
// Always close the streams, even if exceptions were thrown
finally {
if (from != null) try { from.close(); } catch (IOException e) { ; }
if (to != null) try { to.close(); } catch (IOException e) { ; }
}
}
/** A convenience method to throw an exception */
private static void abort(String msg) throws IOException {
throw new IOException("FileCopy: " + msg);
}
}
Search WWH ::




Custom Search