random interviews: create a file system

Design a file system. Write code for file, directory and all necessary classes.

解法1:

这下面的解法来源于这个career cup上的回答
A file system can be represented with a Tree data structure. We can have one class called file (a directory is also a file). This class can track its current directory, its parent directory and files in this directory (in case this file is a special file called directory). Then we can create a class to manage file system which is manipulating the nodes of the tree.

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
package filesystem;
import java.util.ArrayList;
import java.util.Date;
public class FileSystem {
public class file {
private String name;
private long size;
private Date timeStamp;
private file currentDir;
private file parentDir;
// a directory is also a file containing reference to other files
private boolean isDirectory;
public ArrayList<file> subfiles;
// Advanced class members if required
private boolean[] permissions;
private String owner;
private String group;
public file(String name, file currentDir, boolean isDir) {
this.name = name;
this.currentDir = currentDir;
this.timeStamp = new Date();
this.isDirectory = isDir;
this.size = 0; // initial size
this.parentDir = currentDir.getParentDirectory();
if (isDir == true)
this.subfiles = new ArrayList<file>();
}
public void updateTimeStamp() {
this.timeStamp = new Date();
}
public file getParentDirectory() {
return this.parentDir;
}
public void rename(String name) {
this.name = name;
}
}
private file root; // root folder
public FileSystem() {
// every file system should have a root folder
this.root = new file("root", null, true);
}
public void createFile(String name, file curDir, boolean isDir) {
file f = new file(name, curDir, isDir);
curDir.subfiles.add(f);
}
}