文件拷贝
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
public class FileSplitCopy extends Thread{
private File source;
private File target;
private long start;
private long end;
public FileSplitCopy(File source, File target, long start, long end) {
super();
this.source = source;
this.target = target;
this.start = start;
this.end = end;
}
@Override
public void run() {
try (
RandomAccessFile read = new RandomAccessFile(source, "r");
RandomAccessFile write = new RandomAccessFile(target, "rw");)
{
read.seek(start);
write.seek(start);
int count = 0;
byte [] b = new byte [1024];
int len = 0;
System.out.println(getName()+"开始拷贝:"+start);
while((len=read.read(b))!=-1) {
write.write(b,0,len);
count+=len;
if(count>=(end-start) && !"t3".equals(getName()) ) {
break;
}
}
System.out.println(getName()+"拷贝完成");
}
catch (IOException e ) {
e.printStackTrace();
}
}
public static void main(String[] args) {
File source = new File("xxx/xxx");
File target = new File("xxx/xxx");
long item = source.length()/4;
for (int i = 0; i < 4; i++) {
FileSplitCopy fsc = new FileSplitCopy(source,target,i*item,(i+1)*item);
fsc.setName("t"+i);
fsc.start();
}
}
}
实现拷贝文件并且显示拷贝进度(运用守护线程)
package 练习1;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class Test1 extends Thread {
@Override
public void run() {
try {
FileInputStream fis = new FileInputStream(new File("D:/text.txt"));
for (int i = 0; i < fis.available(); i++) {
System.out.println("百分之: "+((i+1)*100/fis.available()));
sleep(50);
}
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws IOException, InterruptedException {
Test1 t = new Test1();
t.setDaemon(true);
t.start();
FileInputStream fis = new FileInputStream(new File("D:/text.txt"));
FileOutputStream fos = new FileOutputStream(new File("D:/接收文件夹/text.txt"));
byte [] b = new byte [1];
int len = 0;
while((len=fis.read(b))!=-1) {
fos.write(b,0,len);
Thread.sleep(50);
}
fos.close();
}
}