Skip to content

Instantly share code, notes, and snippets.

@cokeSchlumpf
Created February 27, 2013 10:42
Show Gist options
  • Save cokeSchlumpf/5047026 to your computer and use it in GitHub Desktop.
Save cokeSchlumpf/5047026 to your computer and use it in GitHub Desktop.
package de.michaelwellner.edu.file;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.channels.FileChannel;
public class FileUtil {
private FileUtil() { }
public static void copyFile(final File src, final File dst) throws IOException {
copyBufferedStream(new FileInputStream(src), new FileOutputStream(dst));
}
public static void copyStreams(final InputStream in, final OutputStream out) throws IOException {
int data = -1;
while ((data = in.read()) != -1) {
out.write(data);
}
out.flush();
}
public static void copyBufferedStream(final InputStream in, final OutputStream out) throws IOException {
final InputStream bin = new BufferedInputStream(in);
final OutputStream bout = new BufferedOutputStream(out);
copyStreams(bin, bout);
}
public static boolean directoryExists(final File directoryToCheck) {
if (directoryToCheck == null) return false;
return directoryToCheck.exists() && directoryToCheck.isDirectory();
}
public static String[] getContents(final File directoryToCheck) {
if (directoryExists(directoryToCheck)) {
final String[] contents = directoryToCheck.list();
if (contents != null) return contents;
}
return new String[0];
}
public static void copyViaChannel(final File src, final File dst) throws IOException {
FileChannel inChannel = new FileInputStream(src).getChannel();
FileChannel outChannel = new FileInputStream(dst).getChannel();
outChannel.transferFrom(inChannel, 0, inChannel.size());
inChannel.close();
outChannel.close();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment