AIM :-使用 Java 中的阻塞 IO 构建多线程应用程序来下载文件。请不要建议我使用非阻塞 IO,我被告知要使用这个。
Issue :-我的代码在下载服务器上托管的文件的客户端计算机上运行良好。但是,问题是我的服务器使用多个线程播种文件。在所有情况下,收到的文件的长度都是准确的,但是文件似乎已损坏。例如,当我下载 PDF 文件时,文件页面已写到最后一页(意味着所有页面都填充了原始内容的部分内容)。当我下载一首歌曲时,它会在整个过程中突然爆发并伴随着这些噪音比特播放到最后。
问题 1:-我应该如何保持完美流畅的下载,以便文件正确播放/打开/读取?我应该在这里解决诸如多线程问题之类的技术问题吗?
我的代码:-
服务器多线程代码:::
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
public class FileServer extends UnicastRemoteObject implements FileServerInitialise{
private String file="";
public FileServer() throws RemoteException{
super();
}
public void setFile(String f){
file=f;
//System.out.println("Length in setFile = "+f);
}
@Override
public boolean login(FileClientInitialise fci) throws RemoteException {
try {
InputStream is = new BufferedInputStream(new FileInputStream(file));
long len = new File(file).length();
System.out.println("Length of File = "+len);
WorkerThread wt1=new WorkerThread(0,len/2,fci,is,file);
wt1.setName("Worker Thread 1");
WorkerThread wt2=new WorkerThread(len/2+1,2*len/2,fci,is,file);
wt2.setName("Worker Thread 2");
//WorkerThread wt3=new WorkerThread(2*len/4+1,3*len/4,fci,is,file);
//wt3.setName("Worker Thread 3");
//WorkerThread wt4=new WorkerThread(3*len/4+1,len,fci,is,file);
//wt4.setName("Worker Thread 4");
wt1.start();
wt2.start();
//wt3.start();
//wt4.start();
wt1.join();
wt2.join();
//wt3.join();
//wt4.join();
return true;
}
catch (InterruptedException iex) {
iex.getMessage();
return false;
}
客户端下载代码:::
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
public class FileClient implements FileClientInitialise {
public static int count = 1;
public static File f;
public static FileOutputStream fos;
public static RandomAccessFile raf;
public static long pointer;
public FileClient (String filename) throws RemoteException, IOException {
super();
FileClient.f= new File(filename);
FileClient.fos = new FileOutputStream(f, true);
//FileClient.raf= new RandomAccessFile(f,"rwd");
FileClient.pointer=0;
}
@Override
public boolean sendData(String filename, byte[] data, int len, String threadName) throws RemoteException{
try{
FileClient.fos.write(data,0,len);
FileClient.fos.flush();
//FileClient.raf.seek(FileClient.pointer);
//FileClient.raf.write(data,0, len);
//FileClient.pointer=raf.getFilePointer();
System.out.println("Done writing data...");
//fos.close();
return true;
}catch(Exception e){
e.getMessage();
return false;
}
}
}
问题2 :-另外,我应该使用RandomAccessFile
达到同样的目的?会不会更好一些?我检查了一下,它运行速度非常慢(几乎慢了 10 倍)。而且,如果我要使用RandomAccessFile
,我应该为每个线程创建一个单独的对象吗?如果在这种情况下建议的话,我应该如何使用它?
如果代码不可能,请给我一个技术描述,代码不必在答案中提及。