Created
July 15, 2014 21:22
-
-
Save ericdcobb/934d1e58d09770b5aa36 to your computer and use it in GitHub Desktop.
An example of a file copy that has progress and the ability to cancel.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import java.io.File; | |
| import java.io.FileInputStream; | |
| import java.io.FileOutputStream; | |
| import java.util.concurrent.ExecutionException; | |
| import java.util.concurrent.ExecutorService; | |
| import java.util.concurrent.Executors; | |
| import java.util.concurrent.Future; | |
| /** | |
| * Created by ericcobb on 7/15/14. | |
| */ | |
| public class Spike { | |
| private static ExecutorService executor = Executors.newCachedThreadPool(); | |
| public static void main(String[] args) throws ExecutionException, InterruptedException { | |
| CopyWorker worker = new CopyWorker(); | |
| Future future = executor.submit(worker); | |
| Thread.sleep(100); | |
| worker.setStopped(true); | |
| future.get(); | |
| } | |
| public static class CopyWorker implements Runnable { | |
| private boolean stopped = false; | |
| public boolean isStopped() { | |
| return stopped; | |
| } | |
| public void setStopped(boolean stopped) { | |
| this.stopped = stopped; | |
| } | |
| @Override | |
| public void run() { | |
| System.out.println("copying file"); | |
| File filein = new File("/Users/ericcobb/Pictures/IMG_0335_1.MOV"); | |
| File fileout = new File("/Users/ericcobb/Pictures/IMG_0335_1_copy.MOV"); | |
| FileInputStream fin; | |
| FileOutputStream fout; | |
| long length = filein.length(); | |
| long counter = 0; | |
| int r = 0; | |
| byte[] b = new byte[1024]; | |
| try { | |
| fin = new FileInputStream(filein); | |
| fout = new FileOutputStream(fileout); | |
| while ((r = fin.read(b)) != -1 && !isStopped()) { | |
| counter += r; | |
| System.out.println(1.0 * counter / length); | |
| fout.write(b, 0, r); | |
| } | |
| } | |
| catch (Exception e) { | |
| System.out.println("foo"); | |
| } | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment