Project

General

Profile

Statistics
| Revision:

root / src / Storage / ChunksManager.java @ 2

History | View | Annotate | Download (2.02 KB)

1
package Storage;
2

    
3

    
4
import java.io.FileInputStream;
5
import java.io.IOException;
6
import java.util.ArrayList;
7

    
8
import static Global.Globals.MAX_CHUNK_SIZE;
9

    
10
public class ChunksManager {
11

    
12

    
13
    ArrayList<Chunk> chunks;
14

    
15
    int peerId;
16

    
17
    int replicationDegree;
18

    
19
    public ChunksManager(String filepath, int rep, int peerId) throws IOException {
20
        this.peerId = peerId;
21
        replicationDegree = rep;
22
        FileInputStream file = new FileInputStream(filepath);
23
        String[] b = filepath.split("/");
24
        this.chunks = new ArrayList<>();
25
        split(file, b[b.length - 1]);
26
    }
27

    
28
    private void split(FileInputStream fileInfo, String fileID) {
29
        int x = 0;
30
        int chunkNo = 0;
31

    
32
        try {
33

    
34
            while (x != -1) {
35
                byte[] a = new byte[MAX_CHUNK_SIZE];
36
                byte[] temp;
37

    
38
                x = fileInfo.read(a);
39

    
40

    
41
                if (x == -1) {
42
                    temp = new byte[0];
43
                    Chunk chunk = new Chunk(chunkNo, temp, peerId, fileID, replicationDegree);
44
                    chunks.add(chunkNo, chunk);
45
                    break;
46
                } else if (x < MAX_CHUNK_SIZE) {
47
                    temp = new byte[x];
48
                    System.arraycopy(a, 0, temp, 0, x);
49
                    Chunk chunk = new Chunk(chunkNo, temp, peerId, fileID, replicationDegree);
50
                    chunks.add(chunkNo, chunk);
51
                    break;
52
                }
53
                Chunk chunk = new Chunk(chunkNo, a, peerId, fileID, replicationDegree);
54
                chunks.add(chunkNo, chunk);
55
                chunkNo++;
56

    
57
            }
58

    
59
            /*if(chunks.get(chunkNo).getInfo().length == MAX_CHUNK_SIZE){
60
                chunkNo++;
61
                chunks.add(chunkNo,new Chunk(chunkNo, new byte[0], peerId));
62
            }*/
63

    
64
            fileInfo.close();
65
        } catch (IOException e) {
66
            //e.printStackTrace();
67
        }
68
    }
69

    
70
    public ArrayList<Chunk> getChunks() {
71
        return chunks;
72
    }
73

    
74
    public int getPeerId() {
75
        return peerId;
76
    }
77
}