www.pudn.com > P2P file system.rar > Downloader.java
package download; /** *Title: P2P File System
* *Description:
* *Copyright: Copyright (c) 2006
* *Company: Fudan University
* * @author Caihong * @student_num 0261097 * @version 1.0 */ import java.net.Socket; import java.io.DataOutputStream; import java.io.File; import java.io.DataInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; import util.FileInformation; public class Downloader extends Thread { public final int DEFAULT_CLIENT_PORT = 8765; private FileInformation serverFile; private String path; private Socket socket = null; private DataOutputStream out = null; private DataInputStream in = null; private File localFile = null; private FileOutputStream fileOutStream = null; byte[] fileData = new byte[4096]; int byteNumber = 0; // Get the related infomation of the indicated file the client wants to download public Downloader(FileInformation serverFile, String path) { this.serverFile = serverFile; this.path = path; } public void run() { try { socket = new Socket(serverFile.getFileLocation(), DEFAULT_CLIENT_PORT); ObjectOutputStream obj = new ObjectOutputStream(socket.getOutputStream()); obj.writeObject(serverFile); obj.flush(); in = new DataInputStream(socket.getInputStream()); out = new DataOutputStream(socket.getOutputStream()); localFile = new File(path + serverFile.getFileName()); if (!localFile.exists()) { fileOutStream = new FileOutputStream(localFile); while ((byteNumber = in.read(fileData)) != -1) { fileOutStream.write(fileData, 0, byteNumber); } fileOutStream.close(); } in.close(); out.close(); socket.close(); } catch (IOException e) { if (localFile.exists()) localFile.delete(); } } }