Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package pl.sweternet.commander.filesystem;
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.FileNotFoundException;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.OutputStream;
- import java.util.ArrayList;
- import java.util.HashSet;
- import java.util.List;
- import java.util.Set;
- import pl.sweternet.commander.FileTableElement;
- public class ResourceManipulator {
- private long size;
- private long done;
- private List<File> sources;
- private File target;
- Set<ProgressListener> listeners;
- public ResourceManipulator() {
- listeners = new HashSet<ProgressListener>();
- size = 0l;
- done = 0l;
- }
- public void addListener(ProgressListener listener) {
- listeners.add(listener);
- }
- private void broadcast() {
- for (ProgressListener listener : listeners) {
- listener.progress(done, size);
- }
- }
- public void copyTo(List<File> sources, File target) throws IOException {
- System.out.println("Coping...");
- List<File> files = new ArrayList<File>();
- String parentString="";
- for (File file : sources) {
- parentString = file.getParent();
- size += FileTableElement.getFileElement(file).getRealSize();
- files.addAll(FileTableElement.getFileElement(file).getFiles());
- }
- for (File file : files) {
- String toCopy = file.getAbsolutePath();
- toCopy = toCopy.replaceFirst(parentString, "");
- copyFile(file, new File(target, toCopy));
- }
- }
- private void copy(File source, File target) throws IOException {
- if (source.isDirectory()) {
- if (!target.exists()) {
- target.mkdir();
- }
- String[] children = source.list();
- for (String file : children) {
- File smth = new File(source, file);
- if (!smth.equals(target))
- copy(smth, new File(target, file));
- }
- } else {
- copyFile(source, target);
- }
- }
- private void copyFile(File source, File target) throws IOException {
- if (source.isDirectory())
- throw new IllegalArgumentException();
- target.getParentFile().mkdirs();
- InputStream in = new FileInputStream(source);
- OutputStream out = new FileOutputStream(target);
- // Copy the bits from instream to outstream
- byte[] buf = new byte[1024];
- int len;
- while ((len = in.read(buf)) > 0) {
- out.write(buf, 0, len);
- done += len;
- broadcast();
- }
- in.close();
- out.close();
- }
- }
Add Comment
Please, Sign In to add comment