I want to create a swing worker that copies file and shows the progress in a progress bar. SIt all works fine except the process() function although I copied paste the code I found in a blog - I don't remember the link to show you, I get compilation errors. Here is my code:
class Copy extends SwingWorker<Void, Void>
{
File src,dest;
InputStream in;
OutputStream out;
JProgressBar bar;
public Copy(File source,File dst)
{
src=source;
dest=dst;
//bar=Br;
progressBar.setValue(0);
}
public Copy(MouseAdapter mouseAdapter) {
// TODO Auto-generated constructor stub
}
protected Void doInBackground() throws Exception
{
System.out.print("Started\n");
InputStream input = null;
OutputStream output = null;
try {
input = new FileInputStream(src);
output = new FileOutputStream(dest);
byte[] buf = new byte[1024];
int bytesRead;
while ((bytesRead = input.read(buf)) > 0) {
output.write(buf, 0, bytesRead);
}
} finally {
input.close();
output.close();
}
progressBar.setVisible(true);
return null;
}
//Here I get the error:
@Override //Description Resource Path Location Type
//The method process() of type Main.Copy must override or implement a supertype method
protected Void process()
{
long expectedBytes = src.length(); // This is the numbe
r of bytes we expected to copy..
byte[] buffer = new byte[1024];
int length;
long totalBytesCopied = 0; // This will track the total number of bytes we've copied
try {
while ((length = in.read(buffer)) > 0){
out.write(buffer, 0, length);
totalBytesCopied += length;
int progress = (int)Math.round(((double)totalBytesCopied / (double)expectedBytes) * 100);
System.out.print(progress);
progressBar.setValue(progress);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// return progress;
}
protected void done()
{
System.out.print("Complete\n");
}
}
}
I cannot understand what I am doing wrong so a little help would be appreciated. Also what is the difference between Void
e.g protected Void doInBackground()
and void
e.g protected void done()
I am currently working in Eclipse and these two have different colours at the editor so there's a difference between them.