--In Java7 or later, if there are no special circumstances, please use the functions of the standard library such as __java.nio.file.Files # copy (Path, Path, CopyOption) __.
--For Java6 or earlier, if possible, use the features of well-established libraries such as Apache Commons and __FileUtils # copyFile (File, File) __ included in Commons-IO.
As of 2017, it should not be necessary to implement it independently, but for some reason it is a case of implementing it independently. If you search the web, you will find code similar to the following.
Sample 1
public static void copyFile(File sf, File df) {
FileChannel sc = null, dc = null;
try {
sc = new FileInputStream(sf).getChannel();
dc = new FileOutputStream(df).getChannel();
dc.transferFrom(sc, 0, sc.size());
} catch (IOException e) {
e.printStackTrace();
} finally {
if (dc != null) try { dc.close(); } catch (IOException e) {}
if (sc != null) try { sc.close(); } catch (IOException e) {}
}
}
This method basically works fine, but depending on the static parser,
sc = new FileInputStream(sf).getChannel();
Where I'm getting this FileChannel in the method chain, I'm warned that __ "FileInputStream may not be closed" __ (same for FileOutputStream)
Fortunately, the Java 6 __java.io.FileInputStream # close () __ documentation says
Closes the file input stream and frees system resources associated with this stream. If this stream has a channel associated with it, close that channel as well.
There is, so let's close FileInputStream (FileOutputStream). Is it something like this (It's okay to close FileChannel as well. Calling both the Close methods of FileInputStream and FileChannel doesn't cause it to crash, though it doesn't make sense).
Sample 2
public static void copyFile(File sf, File df) {
FileInputStream fis = null;
FileOutputStream fos = null;
try {
fis = new FileInputStream(sf);
fos = new FileOutputStream(df);
FileChannel sc = fis.getChannel();
FileChannel dc = fos.getChannel();
dc.transferFrom(sc, 0, sc.size());
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fos != null) try { fos.close(); } catch (IOException e) {}
if (fis != null) try { fis.close(); } catch (IOException e) {}
}
}
Therefore, Sample 2 is less likely to be warned when a static parsing tool is introduced later. If you want to search the web and copy and paste Sample 1, please use Sample 2. ~~ It will be easier for people to maintain later ~~
If you want to implement your own in Java7 or later, [try-with-resources statement](https://docs.oracle.com/javase/jp/8/docs/technotes/guides/language/try-with-resources. Please use html). It will be very simple.
Recommended Posts