Source code: reeb/lazysync/FileTransfer.java
1 // FileTransfer.java
2 package reeb.lazysync;
3
4 import java.net.*;
5 import java.io.*;
6
7 /** FileTransfer provides two methods for sending and receiving binary data
8 as chunks */
9 public class FileTransfer
10 {
11 /** Buffer size constant */
12 private static final int BUFFER_SIZE=16384;
13
14 /** Sends a file to a remote server */
15 public static void sendFile(Socket socket, File file) throws Exception
16 {
17 FileInputStream fis;
18 OutputStream out;
19 byte[] buffer;
20 int amRead, totalRead=0;
21
22 // Create the buffer
23 buffer=new byte[BUFFER_SIZE];
24
25 // Get file input stream
26 fis=new FileInputStream(file);
27
28 // Get socket output stream
29 out=socket.getOutputStream();
30
31 // While amount read not -1
32 while (totalRead<file.length())
33 {
34 // Read in
35 amRead=fis.read(buffer);
36
37 // Write out
38 out.write(buffer,0,amRead);
39
40 // Increment total read
41 totalRead=totalRead+amRead;
42 }
43
44 // Close the file input stream
45 out.flush();
46 fis.close();
47 }
48
49 /** Receives a file from a remote server */
50 public static void receiveFile(Socket socket, File file, long fileSize, long timeStamp) throws Exception
51 {
52 FileOutputStream fos;
53 InputStream in;
54 byte[] buffer;
55 int amRead,totalRead=0;
56
57 // Create the buffer
58 buffer=new byte[BUFFER_SIZE];
59
60 // Get file output stream
61 fos=new FileOutputStream(file);
62
63 // Get socket input stream
64 in=socket.getInputStream();
65
66 // While amount read not -1
67 while (totalRead<fileSize)
68 {
69 // Read in
70 amRead=in.read(buffer);
71
72 // Write out
73 fos.write(buffer,0,amRead);
74
75 // Increment
76 totalRead=totalRead+amRead;
77 }
78
79 // Close the file input stream
80 fos.close();
81
82 // Close the socket
83 in.close();
84 socket.close();
85
86 // Set the timestamp
87 file.setLastModified(timeStamp);
88 }
89 }