-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFolder.java
More file actions
109 lines (70 loc) · 2.33 KB
/
Copy pathFolder.java
File metadata and controls
109 lines (70 loc) · 2.33 KB
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
import java.util.Observable;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
public class Folder extends Observable {
public File file;
public long size;
Folder(String dir){
file = new File(dir);
// getting original folder size
long length = 0;
for (File file : file.listFiles()) {
if (file.isFile())
length += file.length();
}
this.size = length;
}
public File getFile(){
return this.file;
}
public long getSize() {
return this.size;
}
// add a file to the folder being observed, the observer will be notified
public void add(String a){
try {
File myObj = new File(a);
if (myObj.createNewFile()) {
setChanged(); // setting the change before notifyng the observer
notifyObservers("File " + a + " Added");
} else {
System.out.println("File already exists.");
}
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
this.folderSize(file); // checking the size after file addition so that a size change can be notified
}
// delete teh first file in the folder
public void delete(){
File f = file.listFiles()[0];
if (f.delete()) {
// set chaneg and notify
setChanged();
notifyObservers("File " + f + " Deleted ");
} else {
System.out.println("Failed to delete the file.");
}
this.folderSize(this.file);
}
public void folderSize(File directory) {
// measure forlder size
long length = 0;
for (File file : directory.listFiles()) {
if (file.isFile())
length += file.length();
}
if(length != size){
size = length;
setChanged();
notifyObservers("Folder Size Changed" );
}
}
// to test if the folder size change notification works I used this method to add text to a file
public void copyContent(File sour,File dest) throws IOException {
Files.copy(sour.toPath(), dest.toPath());
folderSize(this.file);
}
}