This repository has been archived by the owner on Jan 19, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
FileHandler.java
81 lines (69 loc) · 1.92 KB
/
FileHandler.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package cnt5106c.p2p_file_sharing;
import java.io.RandomAccessFile;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.File;
class FileHandler {
private peerProcess peer;
private RandomAccessFile file;
FileHandler(peerProcess peer) throws FileNotFoundException, IOException {
this.peer = peer;
if(peer.peerInfos.get(peer.peerID).hasFile) {
file = new RandomAccessFile("peer_" + peer.peerID + "/" + peer.fileName, "r");
try {
if(file.length() != peer.fileSize)
System.out.println("Does not have complete file " + peer.fileName + ".");
}
catch(FileNotFoundException e) {
System.out.println("Cannot find " + peer.fileName + ".");
throw e;
}
finally {
file.close();
}
}
try {
File dir = new File("peer_" + peer.peerID);
dir.mkdir();
file = new RandomAccessFile("peer_" + peer.peerID + "/" + peer.fileName, "rw");
file.setLength(peer.fileSize);
}
catch(FileNotFoundException e) {
System.out.println("Failed to open " + peer.fileName + ".");
throw e;
}
}
byte[] readPiece(int pieceIndex) throws IOException {
byte piece[] = null;
try {
int len = peer.pieceSize;
if(pieceIndex == peer.pieceCount - 1)
len = peer.fileSize % peer.pieceSize;
piece = new byte[len];
synchronized(file) {
file.seek(pieceIndex * peer.pieceSize);
file.readFully(piece, 0, len);
}
}
catch(IOException e) {
System.out.println("Failed to read from " + peer.fileName + ".");
throw e;
}
return piece;
}
void writePiece(byte[] piece, int pieceIndex) throws IOException {
try {
int len = peer.pieceSize;
if(pieceIndex == peer.pieceCount - 1)
len = peer.fileSize % peer.pieceSize;
synchronized(file) {
file.seek(pieceIndex * peer.pieceSize);
file.write(piece, 0, len);
}
}
catch(IOException e) {
System.out.println("Failed to write to " + peer.fileName + ".");
throw e;
}
}
}