|
1 | 1 | #Define a class which contains some common operations to file |
2 | 2 | class FileOperator |
3 | 3 |
|
4 | | -def newFile (name, path="./") |
5 | | - begin |
6 | | - puts "Start to create a file..." |
7 | | - file = File.new(name, "w") |
8 | | - rescue StandardError => e |
9 | | - puts e.to_s |
10 | | - ensure |
11 | | - puts "File is closed" |
12 | | - file.close |
| 4 | + CREATE="create" |
| 5 | + DELETE="delete" |
| 6 | + READ="read" |
| 7 | + APPEND="append" |
| 8 | + |
| 9 | + def newFile(name, path="./") |
| 10 | + printStartInfo(CREATE, name) |
| 11 | + begin |
| 12 | + file = File.new(name, "w") |
| 13 | + rescue StandardError => e |
| 14 | + puts e.to_s |
| 15 | + ensure |
| 16 | + closeFile(file) |
| 17 | + end |
13 | 18 | end |
14 | | -end |
15 | 19 |
|
16 | | -def deleteFile(name, path="./") |
17 | | - begin |
18 | | - puts "Start to delete a file..." |
19 | | - File.delete(path+name) |
20 | | - puts "File is deleted successfully." |
21 | | - rescue StandardError => e |
22 | | - puts e.to_s |
| 20 | + def deleteFile(name, path="./") |
| 21 | + printStartInfo(DELETE, name) |
| 22 | + begin |
| 23 | + File.delete(path+name) |
| 24 | + puts "File is deleted successfully." |
| 25 | + rescue StandardError => e |
| 26 | + puts e.to_s |
| 27 | + end |
23 | 28 | end |
24 | | -end |
25 | 29 |
|
26 | | -def readFile(name, path="./") |
27 | | - begin |
28 | | - puts "Start to read a file..." |
29 | | - file = File.open(path+name, "r") |
30 | | - file.readlines |
31 | | - rescue StandarError => e |
32 | | - puts e.to_s |
33 | | - ensure |
34 | | - puts "File is closed" |
35 | | - file.close |
| 30 | + def readFile(name, path="./") |
| 31 | + printStartInfo(READ, name) |
| 32 | + begin |
| 33 | + file = File.open(path+name, "r") |
| 34 | + file.readlines |
| 35 | + rescue StandarError => e |
| 36 | + puts e.to_s |
| 37 | + ensure |
| 38 | + closeFile(file) |
| 39 | + end |
36 | 40 | end |
37 | | -end |
38 | 41 |
|
39 | | -def appendFile(content, name, path="./") |
40 | | - begin |
41 | | - puts "Start to append something..." |
42 | | - file = File.open(path+name, "w") |
43 | | - file.write(content) |
44 | | - rescue StandardError => e |
45 | | - puts e.to_s |
46 | | - ensure |
47 | | - puts "File is closed" |
48 | | - file.close |
| 42 | + def appendFile(content, name, path="./") |
| 43 | + printStartInfo(APPEND, name) |
| 44 | + begin |
| 45 | + file = File.open(path+name, "w") |
| 46 | + file.write(content) |
| 47 | + rescue StandardError => e |
| 48 | + puts e.to_s |
| 49 | + ensure |
| 50 | + closeFile(file) |
| 51 | + end |
49 | 52 | end |
50 | | -end |
51 | 53 |
|
| 54 | + private |
| 55 | + def closeFile(file) |
| 56 | + file.close |
| 57 | + puts "Files is closed" |
| 58 | + end |
| 59 | + |
| 60 | + def printStartInfo(op, fileName) |
| 61 | + puts "Start to #{op} a file named #{fileName}" |
| 62 | + end |
52 | 63 | end |
53 | 64 |
|
54 | 65 | op = FileOperator.new |
|
0 commit comments