-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFileBuffer.java
88 lines (80 loc) · 1.59 KB
/
FileBuffer.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
82
83
84
85
86
87
88
package TextEditor;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Path;
public class FileBuffer extends Buffer {
private Path savePath;
private boolean modified = false;
/**
* Save Buffer into a file.
*
* @throws IOException
*/
public void save() throws IOException {
saveAs(savePath);
}
/**
* Save file to Path.
*
* @throws IOException
*
*/
public void saveAs(Path path) throws IOException {
savePath = path;
File fileOut = new File(savePath.toString());
BufferedWriter bw = new BufferedWriter(new FileWriter(fileOut));
if (!fileOut.exists()) {
fileOut.createNewFile();
}
try {
for (int i = 0; i < getSize(); i++) {
StringBuilder sb = getNthLine(i);
bw.write(sb.toString());
bw.write('\n');
}
} catch (IOException ex) {
throw ex;
} finally {
try {
bw.close();
} catch (IOException ex) {
throw ex;
}
}
}
/**
* Open buffer from a file.
*
* @throws IOException
*
*/
public void open(Path path) throws IOException {
File fileIn = path.toFile();
BufferedReader br = new BufferedReader(new FileReader(fileIn));
try {
String line;
while ((line = br.readLine()) != null) {
insertString(line);
insertChar('\n');
}
br.close();
} catch (IOException ex) {
throw ex;
} finally {
try {
br.close();
} catch (IOException ex) {
throw ex;
}
}
savePath = path;
}
public void insert(char c) {
super.insertChar(c);
modified = true;
}
}