我试图制作一个java程序,用一个线程中的阅读器和另一个线程中的编写器复制文件。该程序在不显示任何错误的情况下工作,但复制的文件与原始文件具有不同的校验和。我无法找到我在程序中犯的错误。该程序复制文本文件,他们似乎没有任何问题。当我尝试复制zip文件时,复制成功完成,但当我尝试提取复制的zip时,它显示zip文件已损坏。有人可以帮助我找到错误。
import java.io.*;
import java.util.concurrent.*;
import java.util.*;
class qu{
qu(byte[] b,int s){
this.b=b;
this.s=s;
}
byte[] b;
int s;
public String toString(){
return s+"";
}
}
class reader implements Runnable{
public byte[] b = new byte[1048576];
String inf;
int s;
long max;
private BlockingQueue<qu> blockingQueue;
public reader(String inf,BlockingQueue<qu> blockingQueue,long max){
this.inf=inf;
this.max=max;
this.blockingQueue=blockingQueue;
}
public void run(){
RandomAccessFile in=null;
try{
in = new RandomAccessFile(inf,"rw");
while((s=in.read(b))!=-1){
blockingQueue.put(new qu(b,s));
}
}catch(Exception e){System.out.println(e);}
finally{
try{
in.close();
}catch(Exception e){System.out.println(e);}
}
}
}
class writer implements Runnable{
public byte[] b = new byte[1048576];
String outf;
int s=0;
long max=0;
private BlockingQueue<qu> blockingQueue;
public writer(String outf,BlockingQueue<qu> blockingQueue,long max){
this.outf=outf;
this.max=max;
this.blockingQueue=blockingQueue;
}
public void run(){
RandomAccessFile out;
qu asd;
System.out.println("Copying..");
try{
out = new RandomAccessFile(outf,"rw");
while(out.getFilePointer()!=max){
asd=blockingQueue.take();
//System.out.println(new String(asd.b));
out.write(asd.b,0,asd.s);
}
out.close();
}catch(Exception e){System.out.println(e);}
}
}
class mul {
public static void main(String[] args) {
String inf = args[0];
String outf = args[1];
File file =new File(inf);
long max = file.length();
BlockingQueue<qu> blockingQueue = new ArrayBlockingQueue<>(64);
if(file.exists()){
long start_time = System.nanoTime();
Thread t1=new Thread(new reader(inf,blockingQueue,max));
t1.start();
Thread t2=new Thread(new writer(outf,blockingQueue,max));
t2.start();
try{
t1.join();
t2.join();
}catch(Exception ex){System.out.println(ex);}
long end_time = System.nanoTime();
double difference = (end_time - start_time) / 1e6;
System.out.println("Time taken: "+difference+"ms");
System.out.println("Copy Completed..");
}else{System.out.println("File not Found");}
}
}
答案 0 :(得分:0)
您需要复制字节数组,例如
public class Qu {
private final byte[] b;
private final int s;
public Qu(byte[] b,int s) {
this.b = Arrays.copyOf(b, b.length);
this.s = s;
}
public String toString(){
return s+"";
}
}